Find weighted characteristics for each row of 2 matrices using apply() function in R

Viewed 26

I have 2 matrices and I want to use apply() to apply weighted median,weighted iqr and weighted quantiles for each row.I want something like:

apply(z, 1, function(x) weighted.mean(x[1:3], x[4:6]))

w<- matrix(c(3, 0, 0, 0,
           0, 1, 2, 0,
           1, 0, 1, 1,
           0, 3, 0, 0,
           0, 0, 2, 1,
           1, 0, 1, 1), nrow = 6, ncol = 6)


x<- matrix(c(-1.569192, 0.0000000, 0, 0.0000000,
             0.000000, -0.6744898, 0, 0.0000000,
             0.000000, 0.0000000, 0, 0.0000000,
             0.000000, 0.0000000, 0, 0.6744898,0,0,0,0,0,0,0,0), nrow = 6, ncol = 6)
1 Answers

To take the weighted mean of each row of x using the row of w having the same index as weights, you can do apply(cbind(x, w), 1, function(x) {weighted.mean(x[1:6], x[7:12])}).

Related