Weighted average across multiple matrices - item by item

I have "mylist" - a list of matrices of the same size:

mylist <- vector("list", 5) 
set.seed(123)
for(i in 1:5){
  mylist[[i]] <- matrix(rnorm(9), nrow = 3)
}

      

I also have a vector of weights "mywgts" - the same length as "mylist"

mywgts <- c(0.8, 0.9, 1, 1.1, 1.2)

      

I need to calculate the weighted average of these matrices - element by element. The result will be a 3-by-3 matrix, where the first element is:

mylist[[1]][1,1]*mywgts[1] + mylist[[2]][1,1]*mywgts[2] + 
mylist[[3]][1,1]*mywgts[3] + mylist[[4]][1,1]*mywgts[4] + 
mylist[[5]][1,1]*mywgts[5]

      

I know how to do this by iterating over all the elements of the matrix. But I am looking for a more economical / elegant R-shaped solution. Also - the actual length of "mylist" is not known in advance.

Thanks for any hint!

+3


source to share


1 answer


You may try

 res <- Reduce(`+`,Map(`*`, mylist, mywgts))
 res
 #         [,1]       [,2]      [,3]
 #[1,]  0.6852912  0.2116715 0.7993867
 #[2,] -0.8815045 -1.9811868 1.2558095
 #[3,]  1.5150166  0.8780412 0.7254080

      

Map

is a wrapper for mapply

which is a multidimensional version sapply

. The ( *

) function is applied to the matching elements of the first ("mylist") and the second elements ("mywgts"), and then uses them Reduce

to sum the matching elements list

.

If you need mean

, split it by the length of "mylist".



  res/length(mylist)

      

Using OP's computation

mylist[[1]][1,1]*mywgts[1] + mylist[[2]][1,1]*mywgts[2] + 
mylist[[3]][1,1]*mywgts[3] + mylist[[4]][1,1]*mywgts[4] + 
mylist[[5]][1,1]*mywgts[5]
#[1] 0.6852912

mylist[[1]][1,2]*mywgts[1] + mylist[[2]][1,2]*mywgts[2] + 
mylist[[3]][1,2]*mywgts[3] + mylist[[4]][1,2]*mywgts[4] + 
mylist[[5]][1,2]*mywgts[5]
#[1] 0.2116715

      

+3


source







All Articles