简体   繁体   English

编码加权平均值(R)

[英]Coding weighted mean (R)

I am having trouble with a piece of my code. 我在一段代码上遇到麻烦。 I want to perform a weighted mean but the value I get is not the value I obtain if I calculate the weighed mean myself. 我想执行加权均值,但是如果我自己计算加权均值,我得到的值不是我获得的值。

Here's how I'm coding the weighted mean: 这是我编码加权均值的方式:

weighted.mean(x = dataset$A[rows], weights = weights) 

The variable is "dataset$A" and the rows I'm using for the weighted mean are listed in "rows" (there are 2 rows). 变量为“ dataset $ A”,我用于加权均值的行列在“行”中(有2行)。 The weights are listed in "weights." 权重在“权重”中列出。

Here's how I'm calculating it myself: 这是我自己计算的方式:

dataset$A_MEAN[rows[1]]*weights[1] + dataset$A_MEAN[rows[2]]*weights[2]

Why is there a difference with these two lines of code? 为什么这两行代码有区别? I tried with the following values: 我尝试使用以下值:

dataset$A = [45792.76, 64984.67] 
weights = [0.3253927, 0.6746073]

The first line of code returns: 55388.71 The second line of code returns: 58739.76 第一行代码返回:55388.71第二行代码返回:58739.76

Thank you so much! 非常感谢! I am sure that this is something minor, but it's driving me nuts! 我敢肯定这是次要的事情,但这让我发疯了!

Check your use of weighted.mean 检查您对weighted.mean的使用

The arguments weights should be w : 参数weights应为w

weighted.mean(x = dataset$A[rows], w = weights) should give you what you want. weighted.mean(x = dataset$A[rows], w = weights)应该给您您想要的东西。

When calling a function, you can make sure that you're using the correct variable names by reading the function's documentation with ?weighted.mean 调用函数时,可以通过使用?weighted.mean阅读函数文档来确保使用正确的变量名。

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

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