【问题标题】:Creating sequences from lists of lists从列表列表创建序列
【发布时间】:2018-02-17 05:15:28
【问题描述】:

我正在尝试从列表中构造序列。

假设我有两个列表:

l1 <- list(c(1,2,3), c(3,4,5,6))
l2 <- list(c(3,4,5), c(5,6,7,8))

我想创建一个列表,其中包含 l1l2 中元素之间的序列,如下所示:

l12
[[1]]
[1] 1 2 3
[2] 2 3 4
[3] 3 4 5

[[2]]
[1] 3 4 5
[2] 4 5 6
[3] 5 6 7
[2] 6 7 8

如果这些只是向量,我会这样做:mapply(seq, l1, l2) 这种情况有类似的解决方案吗?

【问题讨论】:

    标签: r list seq


    【解决方案1】:

    你只需要嵌套另一个mapply

    mapply(
      function(x, y) t(mapply(seq, x, y)),
      l1,
      l2)
    #> [[1]]
    #>      [,1] [,2] [,3]
    #> [1,]    1    2    3
    #> [2,]    2    3    4
    #> [3,]    3    4    5
    #> 
    #> [[2]]
    #>      [,1] [,2] [,3]
    #> [1,]    3    4    5
    #> [2,]    4    5    6
    #> [3,]    5    6    7
    #> [4,]    6    7    8
    

    这也是一个使用purrrtidyverse 解决方案。

    library("purrr")
    
    l12 <- map2(l1, l2, ~map2(.x, .y, seq))
    
    str(l12)
    #> List of 2
    #>  $ :List of 3
    #>   ..$ : int [1:3] 1 2 3
    #>   ..$ : int [1:3] 2 3 4
    #>   ..$ : int [1:3] 3 4 5
    #>  $ :List of 4
    #>   ..$ : int [1:3] 3 4 5
    #>   ..$ : int [1:3] 4 5 6
    #>   ..$ : int [1:3] 5 6 7
    #>   ..$ : int [1:3] 6 7 8
    

    【讨论】:

    • 这对 MCMC 非常有用。感谢分享。
    • 除非你想要一个矩阵,否则Map(或SIMPLIFY = FALSE)代替mapply:Map(function(...) Map(seq, ...), l1, l2)
    • 谢谢,这正是我想要的!我仍然对嵌套应用命令有点担心,但这可以解决问题,所以一切都很好。
    【解决方案2】:

    lapply/mapply 的解决方案可能是

    lapply(seq_along(l1), function(i) mapply(`:`, l1[[i]], l2[[i]]))
    #[[1]]
    #     [,1] [,2] [,3]
    #[1,]    1    2    3
    #[2,]    2    3    4
    #[3,]    3    4    5
    #
    #[[2]]
    #     [,1] [,2] [,3] [,4]
    #[1,]    3    4    5    6
    #[2,]    4    5    6    7
    #[3,]    5    6    7    8
    

    【讨论】:

    • 在 R 中,很少有理由迭代索引,因为您可以只迭代实际元素本身。
    • @alistaire 是的,但在这种情况下,您有两个列表。
    • 所以Map/mapply 而不是lapply/sapply
    猜你喜欢
    • 2021-12-08
    • 2013-04-04
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 2010-09-15
    • 2013-04-18
    • 1970-01-01
    • 2021-08-31
    相关资源
    最近更新 更多