0

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

  • Read about list.files with regex. Related post: https://stackoverflow.com/questions/11433432/how-to-import-multiple-csv-files-at-once – zx8754 Jan 18 '22 at 10:37

1 Answers1

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"))
} 
SamR
  • 8,826
  • 3
  • 11
  • 33
  • With "F[i]" I am expecting to store each CSV file in an individual dataframe named F21, F22, F29, etc. But rather it is creating a list F. How could I solve that? – Muhammad Usama Ashraf Jan 18 '22 at 10:45
  • Assuming each data frame has the same dimensions and types, `my_df <- do.call(rbind, F)`. – SamR Jan 18 '22 at 10:48
  • This is creating only one data frame and binding all the csv files into one. I want each CSV file in a separate dataframe. So, let's say, I want to read Fish21 and save it in dataframe F21, then Fish22 and save it in F22, and so on for all of them. – Muhammad Usama Ashraf Jan 18 '22 at 10:52