看起来你想要一个“平面”列表。为此,您可以使用unlist
with recursive = FALSE
,但根据列表的深度,这可能会很乏味。这是一个例子:
您的数据:
myList <- list(list(a = list("1" = letters[1:3], "2" = letters[1:4])),
list(a = list("1" = letters[1:3], "2" = letters[1:4])))
myList
# [[1]]
# [[1]]$a
# [[1]]$a$`1`
# [1] "a" "b" "c"
#
# [[1]]$a$`2`
# [1] "a" "b" "c" "d"
#
#
#
# [[2]]
# [[2]]$a
# [[2]]$a$`1`
# [1] "a" "b" "c"
#
# [[2]]$a$`2`
# [1] "a" "b" "c" "d"
使用嵌套unlist
s:
unlist(unlist(myList, recursive=FALSE), recursive=FALSE)
# $a.1
# [1] "a" "b" "c"
#
# $a.2
# [1] "a" "b" "c" "d"
#
# $a.1
# [1] "a" "b" "c"
#
# $a.2
# [1] "a" "b" "c" "d"
还有一个名为 LinearizeNestedList ( https://sites.google.com/site/akhilsbehl/geekspace/articles/r/linearize_nested_lists_in_r ) 的漂亮函数,可以在 R 中下载/获取并使用如下(对于任何深度的列表嵌套):
LinearizeNestedList(myList, NameSep=".")
# $`1.a.1`
# [1] "a" "b" "c"
#
# $`1.a.2`
# [1] "a" "b" "c" "d"
#
# $`2.a.1`
# [1] "a" "b" "c"
#
# $`2.a.2`
# [1] "a" "b" "c" "d"
编辑
看来这个问题是How to flatten a list to a list without coercion的副本?
请参阅该问题和一组答案以获取其他有用的解决方案。