[R] for loop to merge .csvs
Steve Lianoglou
mailinglist.honeypot at gmail.com
Thu Feb 10 05:42:31 CET 2011
Hi,
On Wed, Feb 9, 2011 at 11:18 PM, Benjamin Caldwell
<btcaldwell at berkeley.edu> wrote:
> So I needed to merge 17 .csv files, and did so by brute force, but I might
> need to do so again. Anyone have suggestions for a for loop that might do
> the below for me (where a:r are separate .csv files)
>
> ab<-merge(a,b,all=TRUE)
> cd<-merge(c,d,all=TRUE)
> ef<-merge(e,f,all=TRUE)
> gh<-merge(g,h,all=TRUE)
> ij<-merge(i,j,all=TRUE)
> kl<-merge(k,l,all=TRUE)
> no<-merge(m,n,all=TRUE)
> pq<-merge(p,q,all=TRUE)
> abcd<-merge(ab,cd,all=TRUE)
> efgh<-merge(ef,gh,all=TRUE)
> ijkl<-merge(ij,kl,all=TRUE)
> nopq<-merge(no,pq,all=TRUE)
> ah<-merge(abcd,efgh,all=TRUE)
> iq<-merge(ijkl,nopq,all=TRUE)
> aq<-merge(ah,iq,all=TRUE)
> all<-merge(aq,r,all=TRUE)
>
> write.csv(all,file="all.merged.csv")
Imagine you had the names of the csv's in a vector named `files`.
Perhaps something along these lines would work:
R> mergef <- function(x, y) merge(x, y, all=TRUE)
R> dfs <- lapply(files, read.csv)
R> all.dfs <- Reduce(mergef, dfs)
Haven't tested it, but maybe you can give it a whirl and tweak it some
until it works.
--
Steve Lianoglou
Graduate Student: Computational Systems Biology
| Memorial Sloan-Kettering Cancer Center
| Weill Medical College of Cornell University
Contact Info: http://cbio.mskcc.org/~lianos/contact
More information about the R-help
mailing list