Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R sum vectors in list of list

Tags:

r

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.

like image 922
StupidQuestions Avatar asked Dec 14 '25 15:12

StupidQuestions


1 Answers

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

like image 94
akrun Avatar answered Dec 17 '25 10:12

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!