Question

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

Was it helpful?

Solution

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

OTHER TIPS

Use do.call

mapply_sum = function(...){mapply(sum, ...)}
do.call(mapply_sum, o)

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 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top