# [R] sum

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Wed Apr 23 23:50:06 CEST 2003

```Barry Rowlingson <B.Rowlingson at lancaster.ac.uk> writes:

> 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...

>   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:

Didn't someone do an abind() function at some point? (Generalizing
cbind/rbind)

> 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.

l <- foo
apply(array(unlist(l),c(dim(l[[1]]),length(l))),c(1,2),sum)

is a bit shorter.

Even shorter, although I'm not sure better in all senses of the word,
same basic idea:

matrix(apply(sapply(l,c),1,sum),dim(l[[1]]))

However, aren't we ignoring the obvious?:

s<-0;(for(a in l)s<-s+a)

--
O__  ---- Peter Dalgaard             Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics     2200 Cph. N
(*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907

```