【问题标题】:Join 2 nested lists加入 2 个嵌套列表
【发布时间】:2020-03-04 11:28:18
【问题描述】:

我想合并两个列表

list_1 <- list(LIST1 = list(list("a"), list("b"), list("c")))
list_2 <- list(LIST2 = list(list("1"), list("2"), list("3")))

期望的输出:

combined_list <- list()
combined_list[[1]] <- c("a", "1")
combined_list[[2]] <- c("b", "2")
combined_list[[3]] <- c("c", "3")

我有一种讨厌的 for 循环方式来执行此操作,但我想使用 purrr 来清理它吗?任何帮助表示赞赏!

【问题讨论】:

  • 这个操作通常被称为“zip”,但它似乎从 purrr 中消失了。我以为你可以使用map2,但直接调用的结果却非常不同。
  • ……我之前的评论,我错过了多余的中间 list。所以map2 确实 完全按预期工作 - 例如正如在 Calum 的回答中所做的那样,或者相反地通过 first 取消列出和 then 连接:map2(list_1[[1L]], list_2[[1L]], ~ c(unlist(.x), unlist(.y)))

标签: r tidyverse purrr


【解决方案1】:

您的意见有一些奇怪的地方,所以我不确定这是否会完全适用于您的实际情况。如果没有,请扩展您的示例。每个列表只有一个元素,一个,并且各个字母也包含在自己的列表中。我通过使用[[1]] 索引输入列表并使用as.character 展平输出来解决这个问题。

list_1 <- list(LIST1 = list(list("a"), list("b"), list("c")))
list_2 <- list(LIST2 = list(list("1"), list("2"), list("3")))

library(purrr)
combined_list <- map2(list_1[[1]], list_2[[1]], c) %>%
  map(as.character)
str(combined_list)
#> List of 3
#>  $ : chr [1:2] "a" "1"
#>  $ : chr [1:2] "b" "2"
#>  $ : chr [1:2] "c" "3"

reprex package (v0.3.0) 于 2019 年 11 月 7 日创建

【讨论】:

    【解决方案2】:

    这是一个递归连接相同结构的两个嵌套列表并保留该结构的变体

    # 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"))))
    

    然后您可以根据需要展开结构。例如,要获得所需的输出,您可以这样做

    purrr::flatten(purrr::flatten(res))
    # [[1]]
    # [1] "a" "1"
    # 
    # [[2]]
    # [1] "b" "2"
    # 
    # [[3]]
    # [1] "c" "3"
    

    【讨论】:

      【解决方案3】:

      你实际上可以使用这一行:

      map2(list_1,list_2,map2,~paste(c(..1,..2)))[[1]]
      

      输出:

      [[1]]
      [1] "a" "1"
      
      [[2]]
      [1] "b" "2"
      
      [[3]]
      [1] "c" "3"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-21
        • 1970-01-01
        • 2016-03-04
        • 1970-01-01
        相关资源
        最近更新 更多