【问题标题】:in r combine a list of lists into one list在 r 中将列表列表合并为一个列表
【发布时间】:2017-04-07 15:28:44
【问题描述】:

我找不到可以获取子列表所有条目的列表吗?这是一个简单的例子,一个列表或列表:

listoflists <- list("A"=list(c(1,2,3),c(2,34,2)), "B" = list(c(1,2),c(2,3,2,1)), "C" = list(c("sdf",3,2)))
$A
$A[[1]]
[1] 1 2 3

$A[[2]]
[1]  2 34  2


$B
$B[[1]]
[1] 1 2

$B[[2]]
[1] 2 3 2 1


$C
$C[[1]]
[1] "sdf" "3"   "2"

我只是通过使用 for 循环才发现这种可悲的方式:

listofvectors <- list()
for (i in 1:length(listoflists))  {listofvectors <- c(listofvectors, listoflists[[i]])}

【问题讨论】:

  • purrr::flatten(listoflists) 应该这样做。

标签: r list


【解决方案1】:

我们可以使用do.call中的concatenate函数(c)来展平嵌套的list

res <- do.call(c, listoflists)
all.equal(listofvectors, res, check.attributes = FALSE)
#[1] TRUE

或者如cmets中提到的@d.b,unlist和recursive = FALSE也可以工作

unlist(listoflists, recursive = FALSE)

【讨论】:

  • 或unlist(listoflists, recursive = FALSE)
【解决方案2】:

对于没有太多嵌套的具体示例,您也可以使用“purrr”包中的flatten。

library(purrr)
flatten(listoflists)

但是,对于嵌套更深的列表,您没有指定预期的行为。如果你想完全展平嵌套更深的列表,可以看Akhil S Bhel的LinearizeNestedList函数。

例子:

LL <- list(listoflists, listoflists)
str(flatten(LL))  ## Same as `do.call(c, LL)`
# List of 6
#  $ A:List of 2
#   ..$ : num [1:3] 1 2 3
#   ..$ : num [1:3] 2 34 2
#  $ B:List of 2
#   ..$ : num [1:2] 1 2
#   ..$ : num [1:4] 2 3 2 1
#  $ C:List of 1
#   ..$ : chr [1:3] "sdf" "3" "2"
#  $ A:List of 2
#   ..$ : num [1:3] 1 2 3
#   ..$ : num [1:3] 2 34 2
#  $ B:List of 2
#   ..$ : num [1:2] 1 2
#   ..$ : num [1:4] 2 3 2 1
#  $ C:List of 1
#   ..$ : chr [1:3] "sdf" "3" "2"
str(LinearizeNestedList(LL))
# List of 10
#  $ 1/A/1: num [1:3] 1 2 3
#  $ 1/A/2: num [1:3] 2 34 2
#  $ 1/B/1: num [1:2] 1 2
#  $ 1/B/2: num [1:4] 2 3 2 1
#  $ 1/C/1: chr [1:3] "sdf" "3" "2"
#  $ 2/A/1: num [1:3] 1 2 3
#  $ 2/A/2: num [1:3] 2 34 2
#  $ 2/B/1: num [1:2] 1 2
#  $ 2/B/2: num [1:4] 2 3 2 1
#  $ 2/C/1: chr [1:3] "sdf" "3" "2"

【讨论】:

    【解决方案3】:

    下面呢?

    A = list(c(1,2,3),c(2,34,2))
    B = list(c(1,2),c(2,3,2,1))
    C = list(c("sdf",3,2))
    joint_list <- c(A, B, C)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-16
      • 2014-01-27
      • 2014-08-05
      • 1970-01-01
      • 2015-04-01
      • 1970-01-01
      相关资源
      最近更新 更多