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).

I want to read all the CSV files using FOR loop in R. 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.

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

Any help where I am making mistake here?

Thank you


Solution 1:

You are trying to use string interpolation, which does not exist in R.

Look at the output of this:

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:

[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? 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"))
}