Iterate over two nested lists in parallel using purrr functions

I play with some features purrrand discover (to my pleasure) purrr::at_depth(.x, .depth, .f, ...)that shortens for purrr::map(x, . %>% map(fun)).

Question: Is there a similar function or the correct " purrr-way" to do the same thing when I have two nested lists that I want to repeat in parallel

As an example:

x <- list(list(10, 20), list(30, 40))
y <- list(list(1, 2), list(3, 4))

a <- list()
for(i in seq_along(x)) {
   a[[i]] <- map2(x[[i]], y[[i]], `+`) 
}

This works, but rather messy, and I would like to avoid the for loop.

+4
source share
1 answer

+ , map2 , map2 x, y , map2 :

map2(x, y, map2, `+`)

#[[1]]
#[[1]][[1]]
#[1] 11

#[[1]][[2]]
#[1] 22


#[[2]]
#[[2]][[1]]
#[1] 33

#[[2]][[2]]
#[1] 44
+4

Source: https://habr.com/ru/post/1666520/


All Articles