With
xa=aggregate(x$avg,by=list(x$value),FUN=weighted.mean,w=x$weight)
gives me an error
Error in weighted.mean.default(X[[1L]], ...) : 'x' and 'w' must
have the same length
But
weighted.mean(x$avg,w=x$weight);
works fine.
In calculating a simple average, or arithmetic mean, all numbers are treated equally and assigned equal weight. But a weighted average assigns weights that determine in advance the relative importance of each data point. A weighted average is most often computed to equalize the frequency of the values in a data set.
As suggested on an old R thread, you can use by
instead:
wt <- c(5, 5, 4, 1)/15
x <- c(3.7,3.3,3.5,2.8)
xx <- data.frame(avg=x, value=gl(2,2), weight=wt)
by(xx, xx$value, function(x) weighted.mean(x$avg, x$weight))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With