4

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

user1828605
  • 1,723
  • 1
  • 24
  • 63

3 Answers3

8

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

thelatemail
  • 91,185
  • 12
  • 128
  • 188
user1828605
  • 1,723
  • 1
  • 24
  • 63
4

Use do.call

mapply_sum = function(...){mapply(sum, ...)}
do.call(mapply_sum, o)
Ramnath
  • 54,439
  • 16
  • 125
  • 152
3

Variation on @Ramnath's answer:

do.call(mapply,c(sum,o))
#[1]  5 10 15 20 25

However, mapply appears to be substantially slower than using Reduce as in op's answer:

o <- replicate(1000,1:1000,simplify=FALSE)

system.time(Reduce("+", o))
#   user  system elapsed 
#   0.02    0.00    0.01 

system.time(do.call(mapply,c(sum,o)))
#   user  system elapsed 
#   0.94    0.00    0.93 
thelatemail
  • 91,185
  • 12
  • 128
  • 188