我有一个嵌套列表 current_output
,我想取消列出并获得 expected
输出。我想将 current_output
中的列表名称分配给它的子组件。例如,我想将名称 A
分配给 current_output
中的三个子组件,对于 B
和 C 也类似
以匹配`expected.
A1 <- c(1:3)
A2 <- c(4:6)
A3 <- c(7:9)
B1 <- c(1:2)
B2 <- c(3:4)
B3 <- 1
C1 <- c(1:3)
C2 <- 1
C3 <- 1
l1 <- list(list(A1), list(A2), list(A3))
l2 <- list(list(B1),list(B2), list(1))
l3 <- list(list(C1), list(1), list(1))
current_output <- list(l1, l2, l3)
names(current_output) <- c("A", "B", "C")
expected <- list(A1, A2, A3, B1, B2, B3, C1, C2, C3)
names(expected) <- c(rep("A", 3), rep("B", 3), rep("C", 3))
最佳答案
最好有唯一的键,即列表元素的名称 - 遍历嵌套列表,flatten
,然后通过再次连接来invoke
,并通过更改名称从名称中删除后缀数字
library(purrr)
library(dplyr)
library(stringr)
out <- current_output %>%
map(flatten) %>%
invoke(c, .) %>%
setNames(str_remove(names(.), "\\d+"))
-测试
> all.equal(out, expected)
[1] TRUE
或者另一种选择是rrapply
rrapply::rrapply(current_output, how = 'flatten') %>%
setNames(rep(names(current_output), lengths(current_output)))
或者使用base R
,unlist
列表元素,用as.list
将每个元素转换为列表元素,然后从中删除数字带有 sub
的名称并分配回名称
out <- as.list(unlist(current_output))
names(out) <- sub("\\d+$", "", names(out))
关于r - 将嵌套列表中的名称分配给它的子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71903657/