Showing posts with label import multiple files. Show all posts
Showing posts with label import multiple files. Show all posts

Monday, September 28, 2009

Import multiple files into R

I needed to import 144 files in comma separated variable (.csv) format into R. Each individual imported file was to be a dataframe. Obviously, given the nuber of files, automating the process was highly desirable. It took quite a bit of searching before I found a simple solution. The biggest "problem" was finding a way of generating the names of the new R objects. The solution:

Create an R object (called "filelist") giving the names of all the .csv files in the relevant directory.

list.files("/name/the/directory/",pattern='csv$', full.names=T) -> filelist

The "pattern" command lists all files ending in ".csv".

Now its possible to import each of these files using a simple "for" loop. However the point is to reference each cvs file not by its name but by its location in the above "filelist" object. This variable will also be used to generate the name of each of the 144 new dataframes. These will be called named between "thisit1" and "thisit144".


for (var in 1:144) assign(paste("thisit",var,sep=""),read.csv(filelist[var]))