简体   繁体   中英

How to combine elements in a complicated list in R?

I am trying to combine elements in a list in different levels. For example, I have a list generated as below,

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 <- list("table1","comment1",df1)
list2 <- list("table2","comment2",df2)
list3 <- list("table3","comment3",df3)
list <- list(list1,list2,list3)

I want to combine the elements in the list and get a tibble like this,

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

I don't want to get the table by plucking one by one. Is there a simple way to do it?

Thanks!

Try the code below

do.call(
  rbind,
  lapply(
    list,
    function(v) data.frame(table_name = v[[1]], value = v[[3]][[1]]$f2)
  )
)

which gives

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

Using map from purrr

library(purrr)
library(tibble)
map_dfr(list, ~ tibble(table_name = .x[[1]], value = .x[[3]][[1]]$f2))

-output

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM