To read multiple files from a directory and save to a data frame

[This article was first published on R – My thoughts & learnings, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

There are various solution to this questions like these but I will attempt to answer the problems that I encountered with there working solution that either I found or created by my own.
Question 1: My initial problem was how to read multiple .CSV files and store them into a single data frame.
Solution: Use a lapply() function and rbind(). One of the working R code I found here provided by Hadley. The code is

# The following code reads multiple csv files into a single data frame
load_data <- function(path) { 
 files <- dir(path, pattern = '\\*.csv', full.names = TRUE)
 tables <- lapply(files, read.csv)
 do.call(rbind, tables)
}

And then use the function like

> load_data("D://User//Temp")

Filed under: pre-processing, R Tagged: data munging, R

To leave a comment for the author, please follow the link and comment on their blog: R – My thoughts & learnings.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)