Reputation: 2187
I have multiple files which have similar names under different directories. The directory are named similarly for example: dir1 -> dir10.
Under each directory there are files named f1 - f10, and I want to read the first file in each directory.
Could I use a read.csv for example? as I need to use a variable to represent both the directory and file names.
Upvotes: 5
Views: 3280
Reputation: 14093
An alternative for construction of 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 would also allow reading all f*.csv files in those dir*:
file.paths <- Sys.glob ('dir*/*f*.csv')
Upvotes: 10
Reputation: 43245
If David was right with his question, and assuming your working directory is the dir containing all your sub directories...
file.paths <- paste0('dir', 1:10, '/', 'f1.csv')
lapply(file.paths, read.csv)
Should be easy enough to extend this example to your specific situation. The only other function you might want to explore is expand.grid
if you've got 10 files in each of 10 folders:
combos <- expand.grid(1:10, 1:10)
file.paths <- paste0('dir', combos[,1], '/f', combos[,2], '.csv')
Upvotes: 2