简体   繁体   English

从R中的矩阵计算加权平均值

[英]Calculate weighted mean from matrix in R

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:23 行,我想计算加权平均值,其中 1:23 行中的数据是权重,第 24 行是数据。

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!我对编码有点陌生,所以我不太确定该怎么做 - 任何建议都将不胜感激!

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 ):我假设您的第一列是某种索引,而不是用于加权平均值(并且数据存储在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;使用apply并将边距设置为 1,将 apply 的第三个参数中定义的函数apply每一行数据; to calculate the weighted mean, you can use weighted.mean and set the weights to the values of the row.要计算加权平均值,您可以使用weighted.mean并将权重设置为行的值。

你可以做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM