[R] Summing up matrices in a list

Sundar Dorai-Raj sundar.dorai-raj at pdf.com
Wed Mar 16 17:31:11 CET 2005



Vicky Landsman wrote on 3/16/2005 10:21 AM:
> Dear all,
> I think that my question is very simple but I failed to solve it. 
> I have a list which elements are matrices like this:
>  
> 
>>mylist  
> 
> [[1]]
>      [,1] [,2] [,3]
> [1,]    1    3    5
> [2,]    2    4    6
> 
> [[2]]
>      [,1] [,2] [,3]
> [1,]    7    9   11
> [2,]    8   10   12
> 
> I'd like to create a matrix M<-mylist[[1]]+mylist[[2]]
>      [,1] [,2] [,3]
> [1,]    8   12   16
> [2,]   10   14   18
> 
> Is there a way to create M without looping? 
> Thanks a lot, 
> Vicky Landsman. 
> 	[[alternative HTML version deleted]]
> 

Hi Vicky,

This question is in the archives several times:

http://finzi.psych.upenn.edu/R/Rhelp02a/archive/10963.html

My answer last time was the following:

m <- list(matrix(rnorm(4),2,2),
           matrix(rnorm(4),2,2),
           matrix(rnorm(4),2,2))
mexpr <- paste("m[[", seq(along = m), "]]", collapse="+")
eval(parse(text = mexpr))

HTH,

--sundar




More information about the R-help mailing list