在保留索引的同时取消列表的列表 [英] unlisting a list while keeping the indices
问题描述
我有一个列表,可以包含空条目,包含一个元素的条目和包含多个元素的条目.
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(0), integer(0), 11L, 11L, c(6L,
36L), 16L, 16L, integer(0), integer(0))
我想取消列出l1并创建一个数据框,对于空元素,索引将根本不会出现,对于多个元素,索引将出现多次:
I would like to unlist l1 and create a data frame, where for the empty elements the index will not appear at all, and for multiple elements the index will appear multiple times:
df = data_frame(entry = c(2, 5, 6, 7, 7, 8, 9), element = c(11, 11, 11, 6,
36, 16, 16))
例如,在此条目7出现两次,因为列表中有两个元素(6和36).
so for example here entry 7 appears twice because the list has two elements there (6 and 36).
我该怎么做?
推荐答案
我们可以有两个选择.将list
命名为一个,将enframe
命名为tbl_df
,然后将unnest
命名为list
元素. NULL
元素将被自动删除
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
或者在将list
命名为stack
后,将其命名为2列data.frame
Or after naming the list
, stack
it to a 2 column data.frame
stack(setNames(l1, seq_along(l1)))[2:1]
这篇关于在保留索引的同时取消列表的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!