[R] sum
Barry Rowlingson
B.Rowlingson at lancaster.ac.uk
Wed Apr 23 20:37:01 CEST 2003
Luis Silva wrote:
> Dear helpers
>
> I have a list where each element is a matrix (the list is
> obtained with lapply). I want to sum those matrices. Is there a
> function to do that? The sum function sums all the elements...
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
More information about the R-help
mailing list