我想从R中的几个文件中找到列的平均值

时间:2016-10-08 12:49:44

标签: r

这是我的代码,它为任何输入提供NA。请帮我知道我哪里出错。(我是初学者)

pollutantmean <- function(directory, pollutant, id=1:332){
  fname <- sprintf("%s/%03d.csv", directory, id)
  ldf <- lapply(fname, read.csv)
  df <- unlist(ldf)
  a <- matrix(df, ncol = 3)
  dfa <- data.frame(a)
  colnames(dfa)<-c("date", "sulfate", "nitrate")
  mn<-mean(dfa[, pollutant],na.rm=TRUE)
  print(mn)
}

1 个答案:

答案 0 :(得分:1)

最终你想要:

fname <- sprintf("%s/%03d.csv", directory, id)
ldf <- lapply(fname, read.csv)

my.mean <- function(df, pollutant) mean(df[, pollutant], na.rm=TRUE)

pollutant <- "nitrate"  # or "sulfate"
sapply(ldf, my.mean, pollutant) # or
mean(sapply(ldf, my.mean, pollutant))

另外你想要

mean(unlist(sapply(ldf, '[[', pollutant), na.rm=TRUE))