unlisting a list while keeping the indices

后端 未结 2 872
渐次进展
渐次进展 2021-01-25 13:34

I have a list which can have either empty entries, entries containing one elements and entries containing multiple elements.

l1 = list(integer(0), 11L, integer(         


        
相关标签:
2条回答
  • 2021-01-25 14:11

    A "low level" solution:

    data.frame(entry=rep(seq_along(l1),lengths(l1)),element=unlist(l1))
    #  entry element
    #1     2      11
    #2     5      11
    #3     6      11
    #4     7       6
    #5     7      36
    #6     8      16
    #7     9      16
    
    0 讨论(0)
  • 2021-01-25 14:19

    We can have two options. Make the list a named one, enframe it to a tbl_df and then unnest the list element. The NULL elements will be automatically removed

    library(tidyverse)
    l1 %>% 
         set_names(seq_along(.)) %>% 
         enframe %>%
         unnest
    

    Or after naming the list, stack it to a 2 column data.frame

    stack(setNames(l1, seq_along(l1)))[2:1]
    
    0 讨论(0)
提交回复
热议问题