如何在 R 中的复杂列表中组合不同级别的多个元素?

How to combine multiple elements in different levels in a complicated list in R?

我正在尝试组合不同级别列表中的元素。例如,我有一个列表生成如下,

df1<-list(data.frame(f1= c(1:3),f2=c("a","b","c")))
df2<-list(data.frame(f1= c(4:6),f2=c("d","e","f")))
df3<-list(data.frame(f1= c(7:9),f2=c("x","y","z")))

list1 <- tibble("table1","comment1",df1)
list2 <- tibble("table2","comment2",df2)
list3 <- tibble("table3","comment3",df3)
list <- list(list1,list2,list3)

我想组合列表中的元素,得到这样的小标题,

  table_name f1 value
1     table1  1     a
2     table1  2     b
3     table1  3     c
4     table2  4     d
5     table2  5     e
6     table2  6     f
7     table3  7     x
8     table3  8     y
9     table3  9     z

我们可以unnest

library(dplyr)
library(tidyr)
library(purrr)
map_dfr(list,  ~
         .x %>% 
             select(1, 3) %>%
             rename_all(~ c('table_name', 'col1')) %>%
     unnest(c(col1)))

-输出

# A tibble: 9 x 3
#  table_name    f1 f2   
#  <chr>      <int> <chr>
#1 table1         1 a    
#2 table1         2 b    
#3 table1         3 c    
#4 table2         4 d    
#5 table2         5 e    
#6 table2         6 f    
#7 table3         7 x    
#8 table3         8 y    
#9 table3         9 z