如何汇集列表列表中的所有元素?在R

时间:2013-04-04 16:48:53

标签: r list

我有一个列表列表(我认为),因此在列表的每个元素中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"

...

任何想法???

1 个答案:

答案 0 :(得分:3)

看起来你想要一个"扁平的"名单。为此,您可以将unlistrecursive = 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?

重复

查看该问题和其他有用解决方案的答案集。