Home > OS >  bind rows of tibbles present in nested list
bind rows of tibbles present in nested list

Time:12-19

I generated mylist which contains three tibbles.

After creating mylist, how can I create three tibbles A_complete, B_complete and C_complete by binding rows all As, Bs, Cs respectively of mylist.

mylist <- list()
for (iter in 1:10)
{
  mylist[[iter]] <- list(A = tibble(x = runif(5)),
                         B = tibble(x = rep("B", 2)),
                         C = tibble(x = 0:iter))
}

CodePudding user response:

This is a good use for purrr::transpose(). Here's a simple tidyverse solution.

library(tidyverse)
complete_data = mylist %>% 
  transpose() %>% 
  map(reduce, bind_rows)

Output:

> complete_data$A
# A tibble: 50 x 1
        x
    <dbl>
 1 0.905 
 2 0.102 
 3 0.923 
 4 0.504 
 5 0.187 
 6 0.945 
 7 0.0668
 8 0.596 
 9 0.131 
10 0.220 
# ... with 40 more rows

Similarly, complete_data$B and complete_data$C are available.

CodePudding user response:

Using lapply,

A_complete = lapply(mylist, function(x) x[['A']]) %>% bind_rows()
B_complete = lapply(mylist, function(x) x[['B']]) %>% bind_rows()
C_complete = lapply(mylist, function(x) x[['C']]) %>% bind_rows()
  • Related