Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce lists by summing element-wise in purrr

Tags:

r

purrr

tidyverse

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

like image 231
Zafar Avatar asked Apr 11 '17 16:04

Zafar


1 Answers

You can do (s. ?reduce):

   xx %>% reduce(`+`)
   [1]  2  4  6  8 10
like image 107
erc Avatar answered Nov 04 '22 07:11

erc