取消列出子列表并将其元素组合在同一列表下
Unlist a sublist and combine their elements under the same list
我有一个列表列表问题,我只想取消列出底层列表,然后将所有元素组合到同一个列表中。这是示例:
alllist <- list(list(5,c(1,2)),list(3,c(4,5))) #A list of two sublists
alllist
[[1]]
[[1]][[1]]
[1] 5
[[1]][[2]]
[1] 1 2
[[2]]
[[2]][[1]]
[1] 3
[[2]][[2]]
[1] 4 5
#Unlist will unlist all levels
unlist(alllist, recursive = FALSE)
[[1]]
[1] 5
[[2]]
[1] 1 2
[[3]]
[1] 3
[[4]]
[1] 4 5
#But I want to keep the top level such that the result would be:
[1]
5 1 2
[2]
3 4 5
#I would also like to keep the order of the elements from the sublist while unlisting them
我们可以使用lapply
循环遍历list
和unlist
lapply(alllist, unlist)
-输出
#[[1]]
#[1] 5 1 2
#[[2]]
#[1] 3 4 5
我有一个列表列表问题,我只想取消列出底层列表,然后将所有元素组合到同一个列表中。这是示例:
alllist <- list(list(5,c(1,2)),list(3,c(4,5))) #A list of two sublists
alllist
[[1]]
[[1]][[1]]
[1] 5
[[1]][[2]]
[1] 1 2
[[2]]
[[2]][[1]]
[1] 3
[[2]][[2]]
[1] 4 5
#Unlist will unlist all levels
unlist(alllist, recursive = FALSE)
[[1]]
[1] 5
[[2]]
[1] 1 2
[[3]]
[1] 3
[[4]]
[1] 4 5
#But I want to keep the top level such that the result would be:
[1]
5 1 2
[2]
3 4 5
#I would also like to keep the order of the elements from the sublist while unlisting them
我们可以使用lapply
循环遍历list
和unlist
lapply(alllist, unlist)
-输出
#[[1]]
#[1] 5 1 2
#[[2]]
#[1] 3 4 5