fmerhout
fmerhout

Reputation: 164

Creating sequences from lists of lists

I am trying to construct sequences from lists of lists.

Say I have two lists:

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

I want to create a list containing the sequences between the elements in l1 and l2 like so:

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

If these were just vectors, I would do: mapply(seq, l1, l2) Is there a similar solution for this case?

Upvotes: 1

Views: 52

Answers (2)

Rui Barradas
Rui Barradas

Reputation: 76575

A solution with lapply/mapply could be

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

Upvotes: 1

Paul
Paul

Reputation: 9107

You just need to nest another 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

Here is also a tidyverse solution using 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

Upvotes: 3

Related Questions