Reputation: 4145
I'm playing around with some of the purrr
functions and discoverd (to my delight) purrr::at_depth(.x, .depth, .f, ...)
which is short for purrr::map(x, . %>% map(fun))
.
Question: Is there a similar function or a proper "purrr
-way" of doing the same thing when I have two nested lists that I want to iterate over 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 its rather dirty and I'd like to avoid the for loop.
Upvotes: 5
Views: 1199
Reputation: 215137
You have list of lists and +
is not vectorized for lists, you can use map2
two times, the first map2
loops through x, y simultaneously and the second map2
add sub lists in an element wise fashion:
map2(x, y, map2, `+`)
#[[1]]
#[[1]][[1]]
#[1] 11
#[[1]][[2]]
#[1] 22
#[[2]]
#[[2]][[1]]
#[1] 33
#[[2]][[2]]
#[1] 44
Upvotes: 5