Home > OS >  Calculate weighted mean from matrix in R
Calculate weighted mean from matrix in R

Time:06-11

I have a matrix that looks like the following. For rows 1:23, I would like to calculate the weighted mean, where the data in rows 1:23 are the weights and row 24 is the data.

1  107 33 41 22 12 4 122 44 297 123 51 16  7  9  1  1  0
10   5  2  2  1  0 3   4  6  12   3  3  0  1  1  0  0  0
11   1  3  1  0  0 0   4  2   8   3  4  0  0  0  0  0  0
12   2  1  1  0  0 0   2  1   5   6  3  1  0  0  0  0  0
13   1  0  1  0  0 0   3  1   3   5  2  2  0  1  0  0  0
14   3  0  0  0  0 0   3  1   2   3  0  1  0  0  0  0  0
15   0  0  0  0  0 0   2  0   0   1  0  1  0  0  0  0  0
16   0  0  0  0  1 0   0  0   2   0  0  0  0  0  0  0  0
17   1  0  0  0  0 0   0  0   1   0  0  0  0  0  0  0  0
18   1  0  0  0  0 0   0  0   0   0  0  0  0  0  0  0  0
19   0  0  0  0  0 0   1  0   0   0  0  0  0  0  0  0  0
2   80 27 37  5  6 4  97 48 242 125 44 27  7  8  8  0  2
20   0  0  0  0  0 0   0  0   1   0  0  0  0  0  0  0  0
21   0  0  0  0  0 0   0  0   0   0  1  0  0  0  0  0  0
22   0  0  0  0  0 0   0  0   1   0  0  0  0  0  0  0  0
23   0  0  0  0  0 0   0  0   1   0  0  0  0  0  0  0  0
3   47 12 33 12  6 1  63 42 200  96 45 19  6  6  9  2  0
4   45 14 21  9  4 2  54 26 130  71 36 17  8  5  1  0  2
5   42 10 14  6  3 2  45 19  89  45 26  7  4  8  2  1  0
6   17  3 12  5  2 0  18 21  51  41 19 15  5  1  1  0  0
7   16  2  6  0  0 1  14  9  37  23 17  7  3  0  3  0  0
8    9  4  4  2  1 0   7  9  30  15  8  3  3  1  1  0  1
9   12  2  3  1  1 1   6  5  14  12  5  1  2  0  0  1  0
24   0  1  2  3  4 5   6  7   8   9 10 11 12 13 14 15 16

As an example using the top two rows, there would have an additional column at the end indicated the weighted mean.

1  107 33 41 22 12 4 122 44 297 123 51 16  7  9  1  1  0 6.391011
10   5  2  2  1  0 3   4  6  12   3  3  0  1  1  0  0  0 6.232558

I'm a little new to coding so I wasn't too sure how to do it - any advice would be appreciated!

CodePudding user response:

You can do:

apply(df[-nrow(df), ], 1, function(row) weighted.mean(df[nrow(df), ], row))

CodePudding user response:

I'm assuming your first columns is some kind of index and not used for the weighted mean (and the data is stored in matr_dat):

apply(matr_dat[-nrow(matr_dat), -1], 1,
      function(row) weighted.mean(matr_dat[nrow(matr_dat), -1], row))

Using apply and setting the margin to 1, the function defined in the third argument of apply to each row of the data; to calculate the weighted mean, you can use weighted.mean and set the weights to the values of the row.

  • Related