StupidQuestions
StupidQuestions

Reputation: 347

R sum vectors in list of list

I have a list of lists with vectors. It can be generated with

test <- lapply(1:10, function(x){
    list(a=sample(1:5,5),b=sample(1:5,5),c=sample(1:10,5))
})

I now have 10 lists of lists containing a, b, and c. I want to add together all a's, b's, and c's, so I end up with a list of total a, b, and c. How do I do this efficiently? My real data is much larger, and I'm looking to speed it up. I want something that looks like this. Note the numbers are incorrect here.

Upvotes: 3

Views: 367

Answers (1)

akrun
akrun

Reputation: 887961

We can transpose the list and reduce by +

library(purrr)
library(dplyr)
transpose(test) %>% 
      map(reduce, `+`)
#$a
#[1] 35 19 30 33 33

#$b
#[1] 30 27 29 35 29

#$c
#[1] 46 53 59 67 62

NOTE: There was no set.seed. So, results may vary

Upvotes: 4

Related Questions