[英]in r combine a list of lists into one list
我找不到可以獲取子列表所有條目的列表嗎? 這是一個簡單的例子,一個列表 o 列表:
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]])}
我們可以在do.call
使用連接函數 ( c
) 來展平嵌套list
res <- do.call(c, listoflists)
all.equal(listofvectors, res, check.attributes = FALSE)
#[1] TRUE
或者正如評論中提到的unlist
使用recursive = FALSE
unlist
也可以工作
unlist(listoflists, recursive = FALSE)
為了您的具體的例子,它沒有太多的嵌套,你也可以只使用flatten
從“purrr”包。
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"
下面呢?
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.