我试图从具有空值的多个.csv文件中取出平均值。功能是:
pollutantmean <- function (directory, pollutant, id = 1:332) {
#getting and setting wd
currentwd<-getwd()
if (grep(pattern = directory,x = currentwd)) {}
else {setwd(paste("./",directory,"/",sep=""))}
#declaring objects
x<-1
poll<-pollutant
meandata<-c()
#Looping through the files
for (i in id){
#Appending leading zero's to the file names
j<-c()
if (i<10) {j<-paste("00",i,".csv",sep="")}
else if (i>=10 & i<100) {j<-paste("0",i,".csv",sep="")}
else {}
#Adding means of pollutant in meandata
temp <- read.csv(file = j, head = TRUE, sep = ",")
meandata[x] <- mean(temp[,poll], na.rm = TRUE)
x<-x+1
}
#rounding and displaying values
round(mean(meandata),3)}
文件有前导零(例如:001.csv,010.csv,167.csv),所以我添加了一个IF ELSE语句,以便在必要时附加零。它们包含列污损数据,污染物名称为头部。
当我为一个.csv文件运行它时,它会给出正确的输出,但如果我将它用于多个.csv文件,那么它会返回错误/ false值。
对于我出错的地方的任何帮助都将受到高度赞赏。