如何将 R 列表的元素相互附加,但仅限于顶层?

How to append elements of an R list to each other, but only the top level?

我需要附加包含在顶级列表中的列表。其他层次应该保留,并且应该有2个以上的元素。

l <- list(list(1:5), list(6:10))
required <- c(l[[1]], l[[2]])

1) 我们可以 flattencbase R

do.call(c, l)

-输出

#[[1]]
#[1] 1 2 3 4 5

#[[2]]
#[1]  6  7  8  9 10

2) 或者 unlistrecursive = FALSE。还有一个base R解决方案

unlist(l, recursive = FALSE)

3)lapply (base R)

lapply(l, unlist, recursive = FALSE)

4) 或使用 Map(另一个 base R

Map(c, l)

5) 或者 purrr

中的 flatten
library(purrr)
flatten(l)

您也可以使用 mapply():

#Code
mapply(c,l)
[[1]]
[1] 1 2 3 4 5

[[2]]
[1]  6  7  8  9 10

或者 lapply():

#Code 2
lapply(l,unlist)
[[1]]
[1] 1 2 3 4 5

[[2]]
[1]  6  7  8  9 10

sapply():

#Code 3
sapply(l,c)
[[1]]
[1] 1 2 3 4 5

[[2]]
[1]  6  7  8  9 10

所有 base R 个解决方案。