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

Naresh Gurbuxani n@re@h_gurbux@ni @ending from hotm@il@com
Wed Jul 25 08:17:18 CEST 2018


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'))}


More information about the R-help mailing list