Search code examples
rlistappendrowbind

Rowbind List of lists in R


I have a list of lists like out. In each list of list I have a dataframe (with the same structure, i.e. same variables).

out <- replicate(4, rep(list(NULL), 2), simplify = FALSE)

My desire is to rowbind all dataframes belonging to first list of lists, the second together (in my original exercise I have more than a 4 lists of 2 lists... For this example I would do something like the following:

dataframe1 <- rbind(out[[1]][[1]], out[[2]][[1]], out[[3]][[1]], out[[4]][[1]])
dataframe2 <- rbind(out[[1]][[2]], out[[2]][[2]], out[[3]][[2]], out[[4]][[2]])

Any idea on how to do it iteratively and more elegantly?

PS: Sorry for not sharing real data.


Solution

  • Here is an approach using rlist and purr

    do.call(rlist::list.zip, out) %>%
     purrr::map(~ do.call(rbind, .))
    

    Or, with even more purrr:

    library(purrr)
    
    out %>%
      do.call(rlist::list.zip, .) %>%
      map(~ reduce(., rbind))