1

我有一个列表列表(我认为),所以在列表的每个元素中:res[[i]],我有另一个列表,例如:

[[1]]

[[1]]$a

[[1]]$a$`1`
"aa" "bb" "cc"

[[1]]$a$`2`
"aa" "bb" "cc" "dd"

[[2]]

[[2]]$a

[[2]]$a$`1`
"aa" "bb" "cc"

[[2]]$a$`2`
"aa" "bb" "cc" "dd"

...

我想将所有对象合并到一个新列表中,其中只有以下内容:

"aa" "bb" "cc"

"aa" "bb" "cc" "dd"

"aa" "bb" "cc" "cc"

...

任何的想法???

4

1 回答 1

3

看起来你想要一个“平面”列表。为此,您可以使用unlistwith 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"

使用嵌套unlists:

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的副本?

请参阅该问题和一组答案以获取其他有用的解决方案。

于 2013-04-04T17:01:40.647 回答