代码之家  ›  专栏  ›  技术社区  ›  cliu

在列表的同一列表中组合行

  •  0
  • cliu  · 技术社区  · 3 年前

    我有一个包含两个列表的列表,其中第一个有三个元素,第二个有两个元素。我想将同一列表中的元素进行行组合。以下是一些数据:

    list1 <- list(a = c(1,2,3), b = c(4,5,6)) #the first nested list which has three elements
    list2 <- list(a = c(2,4), b = c(5,6)) #the second nested list which has two elements
    alllist<- list(list1, list2) #the combo list that nests list1 and list2
    

    最后,我只是简单地转换了 alllist 到如下列表:

    [[1]]
    [1] 1 2 3
    [1] 4 5 6
    
    [[2]]
    [1] 2 4
    [1] 5 6
    
    1 回复  |  直到 3 年前
        1
  •  4
  •   akrun    3 年前

    在上循环 list rbind

    lapply(alllist, \(x) do.call(rbind, unname(x)))
    

    -输出

    [[1]]
         [,1] [,2] [,3]
    [1,]    1    2    3
    [2,]    4    5    6
    
    [[2]]
         [,1] [,2]
    [1,]    2    4
    [2,]    5    6
    

    或者可以使用 simplify2array

    lapply(alllist, simplify2array)
    
        2
  •  3
  •   PaulS    3 年前

    a. purrr::map dplyr::bind_rows 基于方法,其灵感来自@akrun-first解决方案:

    library(tidyverse)
    
    alllist %>% map(~ bind_rows(.x) %>% unname %>% t) 
    
    #> [[1]]
    #>      [,1] [,2] [,3]
    #> [1,]    1    2    3
    #> [2,]    4    5    6
    #> 
    #> [[2]]
    #>      [,1] [,2]
    #> [1,]    2    4
    #> [2,]    5    6
    
        3
  •  2
  •   deschen    3 年前

    您想要一个二维结构/数组,还是简单地将a和b列表中的值连接起来?如果后者:

    lapply(alllist, function(x) unname(unlist(x)))
    
    [[1]]
    [1] 1 2 3 4 5 6
    
    [[2]]
    [1] 2 4 5 6