Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get sum of the list using mapply in r

Tags:

r

mapply

I have a list of 100 elements, and each element contains 431 elements.

i want to use mapply to sum the values from each list. For example, say I have a list of 5 elements, but each element has another 5 elements.

> o
[[1]]
[1] 1 2 3 4 5

[[2]]
[1] 1 2 3 4 5

[[3]]
[1] 1 2 3 4 5

[[4]]
[1] 1 2 3 4 5

[[5]]
[1] 1 2 3 4 5

> mapply(sum, o[[1]], o[[2]], o[[3]], o[[4]], o[[5]])
[1]  5 10 15 20 25

But how can I do this for say 100 elements. It's not feasible to type in 100 elements as args. Can somebody please help?

Thank you

like image 562
user1828605 Avatar asked Dec 07 '22 04:12

user1828605


2 Answers

I got it. I used Reduce("+", o) instead of mapply.

like image 150
user1828605 Avatar answered Dec 21 '22 23:12

user1828605


Use do.call

mapply_sum = function(...){mapply(sum, ...)}
do.call(mapply_sum, o)
like image 30
Ramnath Avatar answered Dec 21 '22 23:12

Ramnath