Consider first a basic case of map2
usage like this:
listA <- list(1, 2, 3)
listB <- list(4, 5, 6)
map2(listA, listB, sum)
However, what if we have a situation where one input is a list of lists, and the other input is just a list:
listA <- list(list(1, 2, 3),
list(4, 5, 6))
listB <- list(7, 8, 9)
How can I achieve this desired output with purrr
?:
list(list(8, 10, 12),
list(11, 13, 15))
CodePudding user response:
You can use map
twice.
library(purrr)
map(listA, map2, listB, sum)
# this version might show it a bit more clearly
map(listA, ~ map2(.x, listB, sum))
[[1]]
[[1]][[1]]
[1] 8
[[1]][[2]]
[1] 10
[[1]][[3]]
[1] 12
[[2]]
[[2]][[1]]
[1] 11
[[2]][[2]]
[1] 13
[[2]][[3]]
[1] 15