Skip to content

Instantly share code, notes, and snippets.

@abelsonlive
Created May 27, 2012 01:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abelsonlive/2795782 to your computer and use it in GitHub Desktop.
Save abelsonlive/2795782 to your computer and use it in GitHub Desktop.
merge all csv/xls/etc in a directory by a common field, R
#_______________________________________________________________________________#
#| |#
#| !! keep in mind that each data frame must have only one common field name!! |#
#|_____________________________________________________________________________|#
#create the function for csvs
merge.csv = function(mypath){
filenames=list.files(path=mypath, full.names=TRUE)
datalist = lapply(filenames, function(x){read.csv(file=x,header=T, stringsAsFactors=F)})
Reduce(function(x,y) {merge(x,y)}, datalist)
}
# How to use:
data = merge.csv("list/to/dir")
#for xls
merge.xls = function(mypath){
require("gdata")
filenames=list.files(path=mypath, full.names=TRUE)
datalist = lapply(filenames, function(x){read.xls(file=x,header=T)})
Reduce(function(x,y) {merge(x,y)}, datalist)
}
# How to use:
data = merge.xls("list/to/dir")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment