[R] Summing elements in a list

Paul Y. Peng ypeng at math.mun.ca
Fri Oct 31 21:29:56 CET 2003


Angelo Canty wrote:
> 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.

Here is one possibility:

result <- list(
   mat1 = matrix(rowSums(sapply(matlist, function(x)x$mat1) %*% diag(w)), nrow1, ncol1)
   mat2 = matrix(rowSums(sapply(matlist, function(x)x$mat2) %*% diag(w)), nrow2, ncol2)
)

Warning: It doesn't have the readability that the original code has though.

Paul.
-- 
--------------------------------------------------------------------------
   Dr. Paul Y. Peng, Associate Professor            Phone: (709) 737 8080
   Department of Mathematics and Statistics           Fax: (709) 737 3010
   Memorial University of Newfoundland          E-mail: ypeng at math.mun.ca
   St. John's, NL A1C 5S7, Canada             Web: www.math.mun.ca/~ypeng




More information about the R-help mailing list