[R] Using apply function to merge list of data frames

S Ellison S@E|||@on @end|ng |rom LGCGroup@com
Fri Jul 27 13:45:31 CEST 2018


Short answer: do.call()

do.call("rbind", df.list)
will rbind all of the data frames in df.list.

You may have to tidy up row names afterwards, and you will need to make sure that the data frames all have the same column names and each column has the same class, or you'll get unexpected results.

S Ellison

> -----Original Message-----
> From: R-help [mailto:r-help-bounces using r-project.org] On Behalf Of Naresh
> Gurbuxani
> Sent: 25 July 2018 07:17
> To: R-help using r-project.org
> Subject: [R] Using apply function to merge list of data frames
> 
> I have a list whose components are data frames.  My goal is to construct a
> data frame by merging all the list components.  Is it possible to achieve this
> using apply and without a for loop, as used below?
> 
> Thanks,
> Naresh
> 
> mylist <- list(A = data.frame(date = seq.Date(as.Date('2018-01-01'), by =
> 'week',
>                                   length.out = 5), ret = rnorm(5)),
>                B = data.frame(date = seq.Date(as.Date('2018-01-01'), by = 'week',
>                                   length.out = 5), ret = rnorm(5)))
> 
> mydf <- data.frame(date = seq.Date(as.Date('2018-01-01'), by = 'week',
> length.out = 5))
> 
> for(ch in names(mylist)){
>     tempdf <- mylist[[ch]]
>     names(tempdf)[2] <- paste(names(tempdf)[2], ch, sep = '.')
>     mydf <- merge(mydf, tempdf, by = c('date'))}
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-
> guide.html
> and provide commented, minimal, self-contained, reproducible code.


*******************************************************************
This email and any attachments are confidential. Any use...{{dropped:8}}




More information about the R-help mailing list