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.
In order to read multiple CSV files or all files from a folder in R, use data. table package. data. table is a third-party library hence, in order to use data.
R is always pointed at a directory on your computer. You can find out which directory by running the getwd (get working directory) function; this function has no arguments. To change your working directory, use setwd and specify the path to the desired folder.
To list all files in a directory in R programming language we use list. files(). This function produces a list containing the names of files in the named directory. It returns a character vector containing the names of the files in the specified directories.
dirs() method in R language is used to retrieve a list of directories present within the path specified. The output returned is in the form of a character vector containing the names of the files contained in the specified directory path, or returns null if no directories were returned.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With