我想合并两个列表
list_1 <- list(LIST1 = list(list("a"), list("b"), list("c")))
list_2 <- list(LIST2 = list(list("1"), list("2"), list("3")))
Run Code Online (Sandbox Code Playgroud)
combined_list <- list()
combined_list[[1]] <- c("a", "1")
combined_list[[2]] <- c("b", "2")
combined_list[[3]] <- c("c", "3")
Run Code Online (Sandbox Code Playgroud)
我有一个讨厌的for循环方式,但是我想使用purrr清理它吗?任何帮助表示赞赏!
这是一个变体,它递归地连接两个具有相同结构的嵌套列表并保留该结构
# Add additional checks if you expect the structures of .x and .y may differ
f <- function(.x, .y)
if(is.list(.x)) purrr::map2(.x, .y, f) else c(.x, .y)
res <- f( list_1, list_2 )
# ...is identical to...
# list(LIST1 = list(list(c("a","1")), list(c("b","2")), list(c("c","3"))))
Run Code Online (Sandbox Code Playgroud)
然后您可以根据需要展开该结构。例如,要获得所需的输出,您可以这样做
purrr::flatten(purrr::flatten(res))
# [[1]]
# [1] "a" "1"
#
# [[2]]
# [1] "b" "2"
#
# [[3]]
# [1] "c" "3"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |