R迭代读取csv文件 [英] R iterate to read csv files
问题描述
pollutantmean< - function(id){
n< - length(id)
for(i in 1:n){
pol < - read.csv('id [i] .csv')
}
}
污染物(150:160)
csv的文件名类似001.csv,002.csv,100.csv等
001,002和100,这些是id,每个csv有一个id列,如果文件名为001,其内容为1.
当我运行这个代码,控制台提醒我这不是这样的文件id [i]。 csv
第一个问题是第4行,应该替换为
pol< - read.csv(paste0(id [i],.csv))
如果 id [i]
在引号内(简单或双引号),则会被 read.csv
,例如该函数寻找名为 id [i] .csv
的东西,并解释你的错误信息。
但使用此类函数,无论如何, pol
b
$ b
如果你真的想将这些行包装到一个函数中,你需要返回一个列表:
<$ c $对于(i in 1:n){
res [...],对于(i in 1:n),c>污染物平均值< i]] < - read.csv(paste0(id [i],.csv))
}
}
但这里的循环在这里不会很优雅,所以我们可以简单:
pollutionantmean < - function(id){
lapply(id,function(i)read.csv(paste0(i,.csv))
}
甚至(无功能选项),这应该可以工作:
lapply(id,function(i)read.csv(paste0(i,.csv))
pollutantmean <- function(id){ n <- length(id) for (i in 1 : n){ pol <- read.csv('id[i].csv') } } pollutantmean(150:160)
The filenames of csv are like 001.csv, 002.csv, 100.csv etc 001, 002 and 100, these are id, and each csv has a column of id whose content is 1 if the filename is 001.
When I run this code, the console remind me this is no such file id[i].csv
解决方案The first problem is line 4 and it should be replaced by
pol <- read.csv(paste0(id[i], ".csv"))
If
id[i]
is within quotes (either simple or double), it's understood litterally byread.csv
, eg the function is looking for something namedid[i].csv
and which explains your error message.But with such function,
pol
will be overwritten anyway at every step anyway.If you really want to wrapup these lines into a function you need to return a list:
pollutantmean <- function(id){ res <- vector("list", length(id)) for (i in 1:n){ res[[i]] <- read.csv(paste0(id[i], ".csv")) } }
But a loop here would not be very elegant here, so we can simply:
pollutantmean <- function(id){ lapply(id, function(i) read.csv(paste0(i, ".csv")) }
Or even (no function option) this should work:
lapply(id, function(i) read.csv(paste0(i, ".csv"))
这篇关于R迭代读取csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!