Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over two nested lists in parallel using purrr functions

Tags:

r

purrr

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.

like image 891
Manuel R Avatar asked Jan 11 '17 15:01

Manuel R


1 Answers

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
like image 197
Psidom Avatar answered Oct 06 '22 00:10

Psidom