[R] Summing up matrices in a list

Berton Gunter gunter.berton at gene.com
Wed Mar 16 21:01:21 CET 2005


Well, just for fun, and assuming we don't care about efficiency, we can also
use recursion (I don't think this was posted yet):

sumlist<-function(mylist){
## warning -- arguments not checked
if(length(mylist)==2)mylist[[1]] + mylist[[2]]
else mylist[[1]]+ Recall(mylist[-1])
}


Note that this will also fail if the list is too long so that the recursion
is too deep. But it's fun ... and does have the advantage of working for any
'+' method and corresponding class (as the do.call() construction would if
it were bot just a binary operator).

Cheers to all,

-- Bert Gunter
Genentech Non-Clinical Statistics
South San Francisco, CA
 
"The business of the statistician is to catalyze the scientific learning
process."  - George E. P. Box
 
 

> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch 
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Thomas Lumley
> Sent: Wednesday, March 16, 2005 9:02 AM
> To: Adaikalavan Ramasamy
> Cc: R-help
> Subject: Re: [R] Summing up matrices in a list
> 
> On Wed, 16 Mar 2005, Adaikalavan Ramasamy wrote:
> 
> > mylist <- list( matrix(1:6, nc=3), matrix(7:12, nc=3) )
> > do.call("+", mylist)
> >     [,1] [,2] [,3]
> > [1,]    8   12   16
> > [2,]   10   14   18
> >
> 
> Yes, but this works only when the list is of length 2, when
> M<-mylist[[1]]+mylist[[2]] seems preferable.
> 
>  	-thomas
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list