I have two identically sized matrices: m and w that look as follows:
set.seed(5)
m <- matrix(rexp(90), nrow = 3 , ncol = 3)
set.seed(10)
w <- matrix(rexp(90), nrow = 3 , ncol = 3)
I would like to calculate the weighted means of m using w as weights. To be more precise, I would like to do this for each rows (or columns) of m using the same rows (or columns) of w as weights. The results would be ideally stored in a vector. For example:
w_mean_col <- c(weighted.mean(m[,1] , w[,1]) ,
weighted.mean(m[,2] , w[,2]) ,
weighted.mean(m[,3] , w[,3]) )
for the columns, and:
w_mean_row <- c(weighted.mean(m[1,] , w[1,]) ,
weighted.mean(m[2,] , w[2,]) ,
weighted.mean(m[3,] , w[3,]) )
The code is very impractical when working with very large matrices. Would there be better code to do this automatically?