Import multiple files in R as a dataframe

It is often necessary to input multiple files into R at once. However, it is not straightforward and it would be quite frightening.

I myself have spent hours before figuring out. There are many ways to do this. Usually, we are always trying to import the file of the same extension. The most used extensions are “csv”, “dat” , “txt” etc.

Let us suppose you have files of format “csv” on your folder. You can change your working directory to that folder by using

setwd()

Now, let us use this code to import multiple files into a data frame .

We will use plyr library developed by Hadley Wichkam to solve our problem here.

library(plyr)
mydata = ldply(list.files(pattern = “csv”), function(filename) {
dum = read.table(filename,skip=1)

#If you want to add the filename as well on the column

dum$filename = filename
return(dum
})

If you don’t have plyr library installed you can install using the following code:

install.packages(“plyr”)

The code above would import all of your files into the data frame. You can check if the number of data are matching or not by using following:

dim(mydata)

I hope this helps to everyone and probably will save your time. If you have any suggestions please leave your feedback on comments.

Advertisements
This entry was posted in R program and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s