Created
May 27, 2012 01:09
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#_______________________________________________________________________________# | |
#| |# | |
#| !! 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