AlexB
AlexB

Reputation: 3269

rbind multiple lists of dataframes into a list

I am looking for a more elegant or efficient solution of appending multiple lists of data frames into a single list. For simplicity, let's assume we deal with the following case:

my_func <- function(i) {
  # function to generate a list with two data frames
  head(cars, i * 5) -> df1
  head(iris, i * 5) -> df2
  
  return(list(df1, df2))      
}

Let us say we want to execute the function my_func three times and rbind the results in a list:

#output

Map(rbind, my_func(1), my_func(2), my_func(3)) -> out
#this would not be so elegant if we have to run the function many times. 

#or 

for (i in 1:3) {      
  if (i == 1) {        
    out <- my_func(i)        
  } else {        
    out <- Map(rbind, out, my_func(i))
  }      
}

I am not looking for something like this:

do.call(rbind, lapply(1:3, function(i) my_func(i)[[1]])) 
do.call(rbind, lapply(1:3, function(i) my_func(i)[[2]]))

I would like the final output as a list containing the appended data frames.

Thank you.

Upvotes: 1

Views: 297

Answers (2)

akrun
akrun

Reputation: 887971

We can use

map(1:3, my_func) %>% 
     transpose %>% 
     lapply(bind_rows)

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389325

One tidyverse way would be -

library(dplyr)
library(purrr)

map(1:3, my_func) %>% transpose() %>% map(bind_rows)

#[[1]]
#   speed dist
#1      4    2
#2      4   10
#3      7    4
#4      7   22
#5      8   16
#6      4    2
#7      4   10
#8      7    4
#...
#...

#[[2]]
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#1           5.1         3.5          1.4         0.2  setosa
#2           4.9         3.0          1.4         0.2  setosa
#3           4.7         3.2          1.3         0.2  setosa
#4           4.6         3.1          1.5         0.2  setosa
#5           5.0         3.6          1.4         0.2  setosa
#6           5.1         3.5          1.4         0.2  setosa
#...
#...

Upvotes: 1

Related Questions