I'm confused about purrr::map2
. I thought I understood it but I'm stumped here. Can someone help me understand why the first example below is not giving me the output I expected?
library(purrr)
test1 <- list(a = 3, b = 4)
test2 <- list(a = 4:6, b = 5:7)
I want to map along each of these lists and pass the elements stepwise to
a map function
# this does not give what I expect
map2(test1, test2, ~ map(.y, ~ c(.x, .)))
#> $a
#> $a[[1]]
#> [1] 4 4
#>
#> $a[[2]]
#> [1] 5 5
#>
#> $a[[3]]
#> [1] 6 6
#>
#>
#> $b
#> $b[[1]]
#> [1] 5 5
#>
#> $b[[2]]
#> [1] 6 6
#>
#> $b[[3]]
#> [1] 7 7
but if I take the lists element-wise and pass them in, it does what I want
map(test2[[1]], ~ c(test1[[1]], .))
#> [[1]]
#> [1] 3 4
#>
#> [[2]]
#> [1] 3 5
#>
#> [[3]]
#> [1] 3 6
map(test2[[2]], ~ c(test1[[2]], .))
#> [[1]]
#> [1] 4 5
#>
#> [[2]]
#> [1] 4 6
#>
#> [[3]]
#> [1] 4 7
and if I write a function, it also does what I expect
append_to_existing <- function(vec_x, vec_y) {
map(vec_y, ~ c(vec_x, .))
}
# gives desired output
map2(test1, test2, append_to_existing)
#> $a
#> $a[[1]]
#> [1] 3 4
#>
#> $a[[2]]
#> [1] 3 5
#>
#> $a[[3]]
#> [1] 3 6
#>
#>
#> $b
#> $b[[1]]
#> [1] 4 5
#>
#> $b[[2]]
#> [1] 4 6
#>
#> $b[[3]]
#> [1] 4 7
Created on 2020-12-11 by the reprex package (v0.3.0)