0

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). 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

Thank you so much! I am sure that this is something minor, but it's driving me nuts!

Max
  • 21
  • 3

1 Answers1

1

Check your use of weighted.mean

The arguments weights should be w:

weighted.mean(x = dataset$A[rows], w = weights) should give you what you want.

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

C-x C-c
  • 1,261
  • 8
  • 20
  • Oh, I see. Thank you so much! So, if I were to feed the function into a sapply function, I would also write it with a "w", right? For instance: new_values <- sapply(oes16[rows,8:22], weighted.mean, w = weights, na.rm = T) – Max Aug 24 '18 at 19:19
  • No problem. Also, for reference, if this answer or any other one solved your issue, please mark it as accepted. – C-x C-c Aug 24 '18 at 20:18