【问题标题】:Flatten a recursively nested list structure [duplicate]展平递归嵌套列表结构[重复]
【发布时间】:2013-11-17 05:28:54
【问题描述】:

我在编写foreach 循环时犯了一个愚蠢的错误。循环的每次迭代都会返回一个矩阵,除了我给它的参数.combine=list

library(foreach)
nested <- foreach(i = 1:4, .combine=list) %do% {
  matrix(i, 2, 2)
}

结果是一个递归嵌套的列表结构:nested[[2]] 给了我第四个矩阵,nested[[1]][[2]] 给了我第三个矩阵,nested[[1]][[1]][[2]] 给了我第二个矩阵,最后nested[[1]][[1]][[1]] 给了我第一个矩阵:

> nested
[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
     [,1] [,2]
[1,]    1    1
[2,]    1    1

[[1]][[1]][[2]]
     [,1] [,2]
[1,]    2    2
[2,]    2    2


[[1]][[2]]
     [,1] [,2]
[1,]    3    3
[2,]    3    3


[[2]]
     [,1] [,2]
[1,]    4    4
[2,]    4    4

这是一个小例子来演示我的问题是什么样的;我的实际结果是一个嵌套更深的列表。在没有 .combine=list 参数的情况下再次运行我的 foreach 循环,是否有一种简单的方法可以将其展平为每个元素都是矩阵的单个列表?

【问题讨论】:

标签: r list foreach


【解决方案1】:

我曾经遇到过一个名为 LinearizeNestedListsaved it as a Gist 的函数。

听起来像你想要的那样:

## Make sure you are using the development version of "devtools"
## devtools::install_github("devtools")

library(devtools)
source_gist("https://gist.github.com/mrdwab/4205477")
# Sourcing https://gist.github.com/mrdwab/4205477/raw/1bd86c697b89de9941834882f1085c8312076e38/LinearizeNestedList.R
# SHA-1 hash of file is dde479195258dbad9367274ceedbd5a68251478a
LinearizeNestedList(nested)
# $`1/1/1`
#      [,1] [,2]
# [1,]    1    1
# [2,]    1    1
# 
# $`1/1/2`
#      [,1] [,2]
# [1,]    2    2
# [2,]    2    2
# 
# $`1/2`
#      [,1] [,2]
# [1,]    3    3
# [2,]    3    3
#
# $`2`
#      [,1] [,2]
# [1,]    4    4
# [2,]    4    4

【讨论】:

  • 运行source_gist 时出现404 错误。如果我打开 URL 并复制粘贴代码,效果很好!
  • @Manetheran,Git Hub 更改了访问 Gists 的 API,因此您需要使用“devtools”(library(devtools); install.github("devtools"))的开发版本。
猜你喜欢
  • 2012-09-10
  • 2018-06-24
  • 2015-03-25
  • 2011-07-21
  • 2012-07-07
  • 1970-01-01
  • 2015-01-28
  • 1970-01-01
  • 2022-12-11
相关资源
最近更新 更多