Read multiple files in different directories in R

I have several files that have similar names in different directories. The directory is named similarly, for example: dir1 → dir10.

There are files in each directory with the name f1 - f10, and I want to read the first file in each directory.

Can I use read.csv? since I need to use a variable to represent the directory and file name.

+3
source share
2 answers

An alternative to creating file names is sprintf

file.paths <- sprintf ('dir%i/f1.csv', 1:10)

with expand.grid:

grid <- expand.grid (1:4, 1:3)
file.paths <- sprintf ('dir%i/f%i.csv', grid [[1]], grid [[2]])

Or use Sys.glob

file.paths <- Sys.glob ('dir*/f1.csv')

the latter will also allow you to read all f * .csv files in these files:

file.paths <- Sys.glob ('dir*/*f*.csv')
+9
source

If David was right with his question and suggested that your working directory is a directory containing all your subdirectories ...

file.paths <- paste0('dir', 1:10, '/', 'f1.csv')
lapply(file.paths, read.csv)

. , , , , - expand.grid, 10 10 :

combos <- expand.grid(1:10, 1:10)
file.paths <- paste0('dir', combos[,1], '/f', combos[,2], '.csv')
+1

All Articles