Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R编程读取多个.CSV文件_R_Rstudio - Fatal编程技术网

R编程读取多个.CSV文件

R编程读取多个.CSV文件,r,rstudio,R,Rstudio,我正在尝试导入和读取多个csv文件,并找出平均值。当我测试id为1:10时,一切正常。但是,只要我将1更改为不同的数字(如2),就会出现以下错误 --Error in file(file, "rt") : cannot open the connection In addition: Warning message: --In file(file, "rt") : -- cannot open file 'specdata/002.csv': No such file or directory

我正在尝试导入和读取多个csv文件,并找出平均值。当我测试id为
1:10
时,一切正常。但是,只要我将
1
更改为不同的数字(如
2
),就会出现以下错误

--Error in file(file, "rt") : cannot open the connection In addition: Warning message:
--In file(file, "rt") :
--  cannot open file 'specdata/002.csv': No such file or directory
我相信我没有正确定义这个列表,但我不确定。我的代码如下,任何帮助都将不胜感激

pollutantmean <- function(directory=getwd(), pollutant, id = 1:132){

  filename<-c()

  for (i in id){
    filename1<-id[i]
    filename2<-sprintf('%03d.csv', filename1)
  filepath<-file.path(directory,filename2)
  files<-read.csv(filepath,header=TRUE)
  filename<-c(filename,files[[pollutant]])
  }
  pollutantmean<-mean(filename, na.rm=TRUE)
  pollutantmean


}

pollutantmean检查文件路径是否正确。看看我的代码,看看它是否适合你。请注意,我使用list.files在运行for循环之前查找这些CSV

pollutantmean <- function(directory=getwd(), pollutant, id = 1:132){

  #List of your CSV files in directory
  filenames <- list.files(path = directory, pattern = ".csv", full.names = TRUE)

  #If you want to create the file names by yourself, use the following line instead
  #filenames <- paste(id,".csv",sep="")

  #We are going to store the data here
  pollutant_data <- NULL

  #Now read your files from the filenames vector
  for (f in filenames){
    fdata <- read.csv(f, header=TRUE)
    pollutant_data <- c(pollutant_data,fdata$pollutant)
  }

  poll_mean <- mean(pollutant_data, na.rm=TRUE) 

  return(poll_mean)
}

PollutanMean谢谢Emer,这很有效,但我找到了如何让它与sprintf一起工作的方法


我在
filename2中搜索“[r]pollutantmean”