Skip to content
Prev 31065 / 398506 Next

sum

Luis Silva wrote:
Since your matrix elements must be all the same shape (rows x columns) 
for you to sum them, you could store them in an array (see ?array) 
rather than a list. Then all you need do is apply 'sum' to two 
dimensions of the array.

  Here's a one-liner that converts your list into an array (by unlisting 
it and then packing into an array with the right three dimensions) and 
then runs apply(...,c(1,2),sum) to get the answer you want:

  First some sample data:

 > foo
[[1]]
      [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

[[2]]
           [,1]      [,2]      [,3]
[1,] 0.1666667 0.5000000 0.8333333
[2,] 0.3333333 0.6666667 1.0000000

[[3]]
      [,1] [,2] [,3]
[1,]  0.5  0.5  0.5
[2,]  0.5  0.5  0.5

[[4]]
      [,1] [,2] [,3]
[1,] 0.01 0.01 0.01
[2,] 0.01 0.01 0.01

 > 
apply(array(unlist(foo),c(dim(foo[[1]])[1],dim(foo[[1]])[2],length(foo))),c(1,2),sum)
          [,1]     [,2]     [,3]
[1,] 1.676667 4.010000 6.343333
[2,] 2.843333 5.176667 7.510000

I'm sure there's a better way.

Baz