For循环适用于前10个文件,但随后出现错误
我试图编写一个函数:For循环适用于前10个文件,但随后出现错误,r,for-loop,matrix,R,For Loop,Matrix,我试图编写一个函数: pollutantmean<-function(directory,pollutant,id=1:332){ meanpollut<-matrix(nrow = length(id),ncol = 1) for (i in id) { data<-read.csv(dir()[i]) test<-data[,pollutant] meanpollut[i,]<-mean(test,na.rm = TRUE)
pollutantmean<-function(directory,pollutant,id=1:332){
meanpollut<-matrix(nrow = length(id),ncol = 1)
for (i in id) {
data<-read.csv(dir()[i])
test<-data[,pollutant]
meanpollut[i,]<-mean(test,na.rm = TRUE)
}
m<-mean(meanpollut)
m
}
但是当我试着运行这个
pollutantmean("specdata", "nitrate", 70:72)
我得到这个错误:
Error in `[<-`(`*tmp*`, i, , value = mean(test, na.rm = TRUE)) :
subscript out of bounds
“[中的
错误我们可以使用seq\u沿
而不是id中的i
pollutantmean<-function(directory,pollutant,id=1:332){
meanpollut<-matrix(nrow = length(id),ncol = 1)
for (i in seq_along(id)) {
data<-read.csv(dir()[id[i]])
test<-data[,pollutant]
meanpollut[i,]<-mean(test,na.rm = TRUE)
}
m<-mean(meanpollut)
m
}
pollutantmeanUnderstand.我成功地得到了答案,谢谢!
data<-read.csv(dir()[70])
> test<-data[,"nitrate"]
> mean(test,na.rm = TRUE)
pollutantmean<-function(directory,pollutant,id=1:332){
meanpollut<-matrix(nrow = length(id),ncol = 1)
for (i in seq_along(id)) {
data<-read.csv(dir()[id[i]])
test<-data[,pollutant]
meanpollut[i,]<-mean(test,na.rm = TRUE)
}
m<-mean(meanpollut)
m
}