我非常接近完成这个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")
}
}
答案 0 :(得分:0)
我编辑了你的代码,假设在每个.csv文件中你的&#34;硝酸盐&#34;或&#34; sulafte&#34;列包含数字或整数数据类型,即每种物质的量/浓度。
我还修改了for循环,使其与.csv文件结构更加一致。这是代码,希望它有效 - 如果没有,请编辑以隐藏您的.csv文件的str()
函数的输出
pollutantmean = function(directory, pollutant, id = 1:332) {
files_polm = list.files(directory, full.names = TRUE)
dat_3 = numeric()
for (x in id) {
if (x==id[1]) {
dat_3 = read.csv(files_polm[x])
} else{
dat_3 = rbind(dat_3, read.csv(files_polm[x]))
}
}
if (pollutant == "sulfate") {
mean(sub_pol[, "sulfate"], na.rm = TRUE)
} else if (pollutant == "nitrate") {
mean(sub_pol[, "nitrate"], na.rm = TRUE)
} else {
print("Try Again")
}
}