R:警告:当我尝试使用我的功能时得到 NA
R: Warning: get NA when I try to use my function
我是编程新手,正在尝试在 R 中编写一个函数来计算指定监测器列表中污染物(硝酸盐或硫酸盐)的平均值(每个监测器在文件夹中都有自己的 .csv 文件"specdata")。我构造了以下函数:
pollutantmean <- function(directory="specdata", pollutant="sulfate", id=1:332)
{
files_f<-list.files(directory,full.names=TRUE)
d <- data.frame()
for(i in 1:332){
d <- rbind(d,read.csv(files_f[i]))
}
if(pollutant=="sulfate"){
mean(d$Sulfate[which(d$ID==id)], na.rm=TRUE)
}
else{
mean(d$Nitrate[which(d$ID==id)], na.rm=TRUE)
}
}
然后我尝试使用以下方法测试函数:
pollutantmean(directory="specdata",pollutant="sulfate", id=1:10)
然后我收到以下错误:
[1] NA Warning messages:
1: In d$ID == id :
longer object length is not a multiple of shorter object length
2: In mean.default(d$Sulfate[which(d$ID == id)], na.rm = TRUE) :
argument is not numeric or logical: returning NA
这是什么意思?我已经多次检查我的代码,但无法确定问题所在。
谢谢。
在这里,我想我已经实施了评论中的建议,缩短了代码,甚至概括了该功能,以防您想要调查其他污染物(请务必将它们拼写为与 csv 中的拼写相同,包括大写):
pollutantmean <- function(directory="specdata",
pollutant="Sulfate",
id=1:332){
files_f <- list.files(directory,full.names=TRUE)
d <- do.call(rbind, lapply(files_f, read.csv, stringsAsFactors=FALSE))
mean(d[[pollutant]][which(d$ID %in% id)], na.rm=TRUE)
}
希望有用,祝污染物监测顺利
我是编程新手,正在尝试在 R 中编写一个函数来计算指定监测器列表中污染物(硝酸盐或硫酸盐)的平均值(每个监测器在文件夹中都有自己的 .csv 文件"specdata")。我构造了以下函数:
pollutantmean <- function(directory="specdata", pollutant="sulfate", id=1:332)
{
files_f<-list.files(directory,full.names=TRUE)
d <- data.frame()
for(i in 1:332){
d <- rbind(d,read.csv(files_f[i]))
}
if(pollutant=="sulfate"){
mean(d$Sulfate[which(d$ID==id)], na.rm=TRUE)
}
else{
mean(d$Nitrate[which(d$ID==id)], na.rm=TRUE)
}
}
然后我尝试使用以下方法测试函数:
pollutantmean(directory="specdata",pollutant="sulfate", id=1:10)
然后我收到以下错误:
[1] NA Warning messages:
1: In d$ID == id :
longer object length is not a multiple of shorter object length
2: In mean.default(d$Sulfate[which(d$ID == id)], na.rm = TRUE) :
argument is not numeric or logical: returning NA
这是什么意思?我已经多次检查我的代码,但无法确定问题所在。
谢谢。
在这里,我想我已经实施了评论中的建议,缩短了代码,甚至概括了该功能,以防您想要调查其他污染物(请务必将它们拼写为与 csv 中的拼写相同,包括大写):
pollutantmean <- function(directory="specdata",
pollutant="Sulfate",
id=1:332){
files_f <- list.files(directory,full.names=TRUE)
d <- do.call(rbind, lapply(files_f, read.csv, stringsAsFactors=FALSE))
mean(d[[pollutant]][which(d$ID %in% id)], na.rm=TRUE)
}
希望有用,祝污染物监测顺利