Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read multiple files under different directories in R

Tags:

r

readfile

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.

like image 916
lolibility Avatar asked May 08 '12 15:05

lolibility


People also ask

How do I read multiple files in a folder in R?

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.

How do I navigate folders in R?

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.

How do I see all working directory in R?

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.

How do I get a list of directories in R?

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.


1 Answers

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')
like image 173
cbeleites unhappy with SX Avatar answered Nov 15 '22 06:11

cbeleites unhappy with SX