[R] Summing elements in a list

Angelo Canty canty at math.mcmaster.ca
Fri Oct 31 20:16:31 CET 2003


Hi,

Suppose that I have a list where each component is a list of two
matrices.  I also have a vector of weights.  How can I collapse my
list of lists into a single list of two matrices where each matrix
in the result is the weighted sum of the corresponding matrices.

I could use a loop but this is a nested calculation so I was hoping
there is a more efficient way to do this.  To help clarify, here is
the code I would use with a for loop

result <- list(mat1=matrix(0,nrow1,ncol1),
               mat2=matrix(0,nrow2,ncol2))
for (i in seq(along=matlist)) {
   result$mat1 <- result$mat1+w[i]*matlist[[i]]$mat1
   result$mat2 <- result$mat2+w[i]*matlist[[i]]$mat2
}

I apologise if this is a trivial question.  Unfortunately I don't have
my copy of V&R S Programming to hand.

Thanks for your help,
Angelo
-- 
------------------------------------------------------------------
|   Angelo J. Canty                Email: cantya at mcmaster.ca     |
|   Mathematics and Statistics     Phone: (905) 525-9140 x 27079 |
|   McMaster University            Fax  : (905) 522-0935         |
|   1280 Main St. W.                                             |
|   Hamilton ON L8S 4K1                                          |




More information about the R-help mailing list