6
votes

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

1
%>% is not a base R operator. It is part of the magrittr package. Base R would be Reduce("+", xx) or do.call("+", xx).lmo
Not a useful comment, but I've edited my question nonetheless.Zafar
It's not my intention to troll, but note that the initial statement in the R tag says "R is a free, open-source programming language and software environment for statistical computing, bioinformatics, and graphics. Please supplement your question with a minimal reproducible example. Use dput() for data and specify all non-base packages with library calls."lmo

1 Answers

7
votes

You can do (s. ?reduce):

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