从列表的列表创建序列

Creating sequences from lists of lists

我正在尝试从列表的列表构建序列。

假设我有两个列表:

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) 这种情况有类似的解决方案吗?

你只需要嵌套另一个 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

这里还有一个 tidyverse 使用 purrr 的解决方案。

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

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