Zafar
Zafar

Reputation: 2016

Reduce lists by summing element-wise in purrr

I'm trying to use purrr to sum list elements with the same index. This can be achieved in base R using the following:

xx <- list(a = c(1,2,3,4,5), b = c(1,2,3,4,5))
Reduce("+", xx)

which provides:

[1]  2  4  6  8 10

Great! That's what I need, but I want to do it all in purrr. %>% reduce(sum) gives a single value back. Does anyone know the syntax to do this in purrr?

Edit- I forgot to specify, this needs to work for n lists.

Dan

Upvotes: 6

Views: 1101

Answers (1)

erc
erc

Reputation: 10123

You can do (s. ?reduce):

   xx %>% reduce(`+`)
   [1]  2  4  6  8 10

Upvotes: 7

Related Questions