Easily Import Multiple Files into R

If you work with a large amount of data, you’ll often be faced with loading many files (EXCEL, SAS, etc.) into R as the very first step of your project. And often, if your clients send you a large amount of data, they would like to know right away if everything loaded correctly — or, it is in your best interest to make sure everything’s perfect before the person who pulled the data forgets what they pulled or moves on to other work.  Unfortunately, loading each file in a data set can be quite tedious:

attendance_2014_C15 <- read.csv(“attendance_2014_C15.csv”, stringsAsFactors=FALSE)
attendance_2014_C14 <- read.csv(“attendance_2014_C14.csv”, stringsAsFactors=FALSE)
attendance_2015_C15 <- read.csv(“attendance_2015_C15.csv”, stringsAsFactors=FALSE)
attendance_2015_C14 <- read.csv(“attendance_2014_C14.csv”, stringsAsFactors=FALSE)
grades_2014_s1_C14 <- read.csv(“grades_2014_s1_C14.csv”, stringsAsFactors=FALSE)
grades_2014_s2_C14 <- read.csv(“grades_2014_s2_C14.csv”, stringsAsFactors=FALSE)

….etc.  Typically we import these data using copy/paste or just typing in the code. This can be tedious if there are more than a few files…. and it’s a way to inadvertently introduce errors (there’s an error in the code above, see if you spot it, that would not be caught by R).

Well, I’m here to introduce you to a new and easy method for getting all the data from a directory and saving it to your R global environment.

And it just takes a few line of code.

# get file names from directory

   files <- list.files()

# split to save names; name for data frame will be first element

   names <- strsplit(files, "\\.")

# now get the files

for (i in 1:length(files)) { # for each file in the list
   fileName <- files[[i]] # save filename of element i
   dataName <- names[[i]][[1]] # save data name of element i
   tempData <- read.csv (fileName, stringsAsFactors=FALSE) # read csv file
   assign (dataName, tempData, envir=.GlobalEnv)  # assign the results of file to the data named

}