Shortening lists by summing over elements in purrr

I am trying to use purrrto summarize list items with the same index. This can be achieved in the R base 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

Fine! This is what I need, but I want to do it all in purrr. %>% reduce(sum)returns a single value. Does anyone know the syntax for this in purrr?

Edit - I forgot to indicate this should work for n lists.

Dan

+4
source share
1 answer

You can do (s. ?reduce):

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

Source: https://habr.com/ru/post/1674586/


All Articles