【发布时间】:2015-05-15 03:06:01
【问题描述】:
我非常接近完成这个 R 程序,但结果一直给我 NaN。它应该在一堆 csv 文件中找到硝酸盐或硫酸盐的平均值。有谁知道代码可能出错的地方吗?以下是程序说明。这似乎很不言自明,只是我有点难过。如果您需要更多详细信息,请告诉我。谢谢
pollutantmean <- function(directory, pollutant, id = 1:332) {
## 'directory' is a character vector of length 1 indicating
## the location of the CSV files
## 'pollutant' is a character vector of length 1 indicating
## the name of the pollutant for which we will calculate the
## mean; either "sulfate" or "nitrate".
## 'id' is an integer vector indicating the monitor ID numbers
## to be used
## Return the mean of the pollutant across all monitors list
## in the 'id' vector (ignoring NA values)
}
pollutantmean = function(directory, pollutant, id = 1:332) {
files_polm = list.files(directory, full.names = TRUE)
dat_3 = numeric()
for (x in id) {
dat_3 = rbind(dat_3, read.csv(files_polm[x]))
}
if (pollutant == "sulfate") {
sub_pol = dat_3[which(dat_3[, "sulfate"] == "sulfate"), ]
mean(sub_pol[, "sulfate"], na.rm = TRUE)
}
else if (pollutant == "nitrate") {
sub_pol = dat_3[which(dat_3[, "nitrate"] == "nitrate"), ]
mean(sub_pol[, "nitrate"], na.rm = TRUE)
}
else {
print("Try Again")
}
}
【问题讨论】:
-
你能把这个设为reproducible example吗?这将使我们更容易尝试并找出问题所在。
-
如果你让每个步骤都工作并然后将它放入一个函数中会更容易调试
-
用文字描述你想要什么也会有所帮助。您真的需要查看名为“硫酸盐”的列来查找值为“硫酸盐”的行吗?没有看到你的数据就不可能说出来。
-
我用解释编辑了我上面的原始帖子。我很抱歉没有提供更多细节。谢谢。
-
您在某处有一个空组。
mean(numeric(0))是NaN...