我在air中有以下代码,目的是执行以下操作:提供我在目录中指定所有.csv文件的列的平均值
meanColumn <- function(directory, pol, id=1:2){
getfiles <- list.files(directory, full.names=TRUE)
for(i in id) {
print("hello") #just to check whether looping goes fine
file<- read.csv(getfiles[i]) #store all results
colPol <- file[, pol] #get the second column of the .csv file
x <- mean(colPol) #get the mean of this column
print(x) #print it :)
}
getfiles #just for checking
}
当我像这样运行这个函数meanColumn(“Assignment1”,2)时,我得到以下输出。
关于我哪里出错的任何想法?
答案 0 :(得分:0)
我已经得到了答案。我忘了过滤掉&#34; NA&#34;值。这有效:
meanColumn <- function(directory, pol, id=1:2){
getfiles <- list.files(directory, full.names=TRUE)
for(i in id) {
print("hello")
file<- read.csv(getfiles[i])
col_mean_with_NA <- file[, pol]
colPol <- col_mean_with_NA[!is.na(col_mean_with_NA)]
x <- sum(colPol)
print(x)
}
getfiles
}