代码之家  ›  专栏  ›  技术社区  ›  stevec Zxeenu

函数将多个列表合并为单个列表?

  •  1
  • stevec Zxeenu  · 技术社区  · 3 年前

    l 这是一个列表列表。

    a <- list(c(1,2,3))
    b <- list(c(4,5,6), c(7,8,9))
    c <- list(c(10,11,12), c(13,14,15), c(16,17,18))
    
    l <- list(a, b, c)
    

    是一个列表列表,其中每个列表本身至少包含一个列表。

    问题

    如何制作一个函数,将所有最低级别的列表提取到单个列表中?

    # Goal
    list(c(1,2,3), c(4,5,6), c(7,8,9), c(10,11,12), c(13,14,15), c(16,17,18))
    

    笔记:

    • 这个例子是一个最小的可重复的例子,对于这个例子来说,硬编码解决方案是可能的,但是解决方案的通用性很重要,因为真正的问题有成千上万个列表,每个列表都包含未知数量的列表-所以硬编码的解决方案肯定不会扩展!

    到目前为止,我已经尝试了一些事情

    一些不成功的尝试,主要是使用 sapply() unlist() :

    sapply(l, function(x) { unlist(x) })
    # [[1]]
    # [1] 1 2 3
    # 
    # [[2]]
    # [1] 4 5 6 7 8 9
    # 
    # [[3]]
    # [1] 10 11 12 13 14 15 16 17 18
    
    unlist(a)
    # [1] 1 2 3
    
    # unlist() seems to combine the elements of multiple lists into one list (not desired here)..
    unlist(b)
    # [1] 4 5 6 7 8 9
    

    我以为 recursive = FALSE

    unlist(b, recursive = FALSE)
    # [1] 4 5 6 7 8 9
    
    2 回复  |  直到 3 年前
        1
  •  2
  •   jay.sf    3 年前

    使用 unlist ,在初始列表中是非递归的。

    unlist(l, recursive=FALSE)
    # [[1]]
    # [1] 1 2 3
    # 
    # [[2]]
    # [1] 4 5 6
    # 
    # [[3]]
    # [1] 7 8 9
    # 
    # [[4]]
    # [1] 10 11 12
    # 
    # [[5]]
    # [1] 13 14 15
    # 
    # [[6]]
    # [1] 16 17 18
    
        2
  •  1
  •   jpsmith    3 年前

    只用 unlist() :

    a <- list(c(1,2,3))
    b <- list(c(4,5,6), c(7,8,9))
    c <- list(c(10,11,12), c(13,14,15), c(16,17,18))
    l <- list(a, b, c)
    
    l.want <- list(c(1,2,3), c(4,5,6), c(7,8,9), c(10,11,12), c(13,14,15), c(16,17,18))
    
    #Use unlist
    l.func <- unlist(l, recursive = F)
    
    all.equal(l.want, l.func)
    # TRUE