Jojo Ono Jojo Ono - 1 month ago 5x
R Question

Importing multiple .csv files into R

Suppose we have a folder containing multiple data.csv files, each containing the same number of variables but each from from different times.

Is there a way in R to import them all simultaneously rather than having to import them all individually?

My problem is that I have around 2000 data files to import and having to import them individually just by using the code:

read.delim(file="filename", header=TRUE, sep="\t")

is not very efficient.


Something like the following should work:

temp = list.files(pattern="*.csv")
myfiles = lapply(temp, read.delim)

This assumes that you have those CSVs in a single directory--your current working directory--and that all of them have the lower-case extension .csv.


Quick and dirty solution to get separate data.frames ("dirty" because I haven't bothered to clean up the .csv extension, but that's easy enough to do with some regex):

temp = list.files(pattern="*.csv")
for (i in 1:length(temp)) assign(temp[i], read.csv(temp[i]))

Or, without assign, and to demonstrate (1) how the file name can be cleaned up and (2) show how to use list2env, you can try the following:

temp = list.files(pattern="*.csv")
  lapply(setNames(temp, make.names(gsub("*.csv$", "", temp))), 
         read.csv), envir = .GlobalEnv)