【问题标题】:How to unlist nested lists while keeping vectors如何在保留向量的同时取消列出嵌套列表
【发布时间】:2019-07-17 08:44:50
【问题描述】:

我想取消列出一个嵌套列表,其中包含一些项目作为向量。问题是 unlist 也会拆分这些向量。我怎样才能将它们保留为单个项目?

a) 上一级(unlist 参数:recursive = F)

b) 所有级别(未列出参数:recursive = T)

示例如下:

list0 <- list(c(1,2),
              list(3,
                   c(4,5)
                   )
              )

> list0
[[1]]
[1] 1 2

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

[[2]][[2]]
[1] 4 5

如果我们取消列出一个级别:

list1 <- unlist(list0, recursive = F)

我们得到:

> list1
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4 5

但是,由于我想保持向量不变,我想得到:

[[1]]
[1] 1 2

[[2]]
[1] 3

[[3]]
[1] 4 5

也许一种方法是使用 for 循环,但我想如果列表数量很多,那会很慢。

谁能给我一些提示,好吗?

提前致谢

【问题讨论】:

标签: r list vector


【解决方案1】:

对于您的示例,下面的代码给出了预期的结果。

f <- function(x){
  if(is.atomic(x)){
    list(x)
  }else{
    x
  }
}

unlist(lapply(list0, f), recursive=FALSE)

但也许您需要一些适用于更多嵌套级别的东西,例如:

f <- function(x){
  if(is.atomic(x)){
    list(x)
  }else{
    x
  }
}
g <- function(L){
  out <- unlist(lapply(L, f), recursive=FALSE)
  while(any(sapply(out, is.list))){
    out <- g(out)
  }
  out
}

list1 <- list(c(1,2),
              list(3, c(4,5)), 
              list(6, list(c(7,8)))
)
list1_flattened <- g(list1)

给出:

> list1
[[1]]
[1] 1 2

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

[[2]][[2]]
[1] 4 5


[[3]]
[[3]][[1]]
[1] 6

[[3]][[2]]
[[3]][[2]][[1]]
[1] 7 8    

> list1_flattened
[[1]]
[1] 1 2

[[2]]
[1] 3

[[3]]
[1] 4 5

[[4]]
[1] 6

[[5]]
[1] 7 8

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    相关资源
    最近更新 更多