简体   繁体   English

For循环从不同目录读取R中的多个csv文件

[英]For loop to read multiple csv files in R from different directories

I have multiple directories within one common directory and each containing a CSV file (and some other files too).我在一个公共目录中有多个目录,每个目录都包含一个 CSV 文件(以及其他一些文件)。

I want to read all the CSV files using FOR loop in R.我想在 R 中使用 FOR 循环读取所有 CSV 文件。 The name of each directory (within the common directory) are not in sequence however the name of each CSV file within the directory is the same as the directory it is in. I wrote the following simple code but it gives me error.每个目录的名称(在公共目录中)不是按顺序排列的,但是目录中每个 CSV 文件的名称与其所在的目录相同。我编写了以下简单代码,但它给了我错误。

files <- c(21,22,29,30,34,65,66,69,70,74)

for(i in files) {                                             # Loop over character vector
  F[i] <- read.csv("F:/Fish[i]/Fish[i].csv")
} 

Error in file(file, "rt"): cannot open the connection In addition: Warning message: In file(file, "rt"): cannot open file '/Fish[i]/Fish[i].csv': No such file or directory文件中的错误(文件,“rt”):无法打开连接另外:警告消息:在文件(文件,“rt”)中:无法打开文件'/Fish[i]/Fish[i].csv':否这样的文件或目录

Any help where I am making mistake here?我在这里犯错的地方有什么帮助吗?

Thank you谢谢

You are trying to use string interpolation, which does not exist in R.您正在尝试使用 R 中不存在的字符串插值。

Look at the output of this:看看这个的output:

files <- c(21,22,29,30,34,65,66,69,70,74)

for(i in files) {                                             # Loop over character vector
  print("F:/Fish[i]/Fish[i].csv")
} 

Output: Output:

[1] "F:/Fish[i]/Fish[i].csv"
[1] "F:/Fish[i]/Fish[i].csv"
[1] "F:/Fish[i]/Fish[i].csv"
[1] "F:/Fish[i]/Fish[i].csv"
[1] "F:/Fish[i]/Fish[i].csv"
[1] "F:/Fish[i]/Fish[i].csv"
[1] "F:/Fish[i]/Fish[i].csv"
[1] "F:/Fish[i]/Fish[i].csv"
[1] "F:/Fish[i]/Fish[i].csv"
[1] "F:/Fish[i]/Fish[i].csv"

Additionally, what is F ?另外,什么是F If it is a list, you will need to use double square brackets:如果是列表,则需要使用双方括号:

for(i in files) {                                             # Loop over character vector
 F[[i]] <- read.csv(paste0("F:/Fish",i,"/Fish", i, ".csv"))
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM