如何将 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) 我们可以 flatten
和 c
从 base R
do.call(c, l)
-输出
#[[1]]
#[1] 1 2 3 4 5
#[[2]]
#[1] 6 7 8 9 10
2) 或者 unlist
和 recursive = 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
个解决方案。
我需要附加包含在顶级列表中的列表。其他层次应该保留,并且应该有2个以上的元素。
l <- list(list(1:5), list(6:10))
required <- c(l[[1]], l[[2]])
1) 我们可以 flatten
和 c
从 base R
do.call(c, l)
-输出
#[[1]]
#[1] 1 2 3 4 5
#[[2]]
#[1] 6 7 8 9 10
2) 或者 unlist
和 recursive = 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
个解决方案。