7

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.

4
  • 1
    When you use aggregate, you split your data set in the chunks. So weighted mean is operating on a chunk of data. So the weights should be from this chunk. You however supply the weights from all data. Hence the error message.
    – mpiktas
    Aug 22, 2011 at 10:31
  • something like this should work: aggregate(x[,c("avg","weight")],by=list(x$value),FUN=function(d)weighted.mean(d[,1],d[,2]))
    – mpiktas
    Aug 22, 2011 at 10:34
  • Could you give this question some fitting tags? (If this language is R, the r tag seems right.) Aug 22, 2011 at 14:08
  • possible duplicate of Aggregate and Weighted Mean in R
    – John
    Mar 30, 2015 at 22:26

2 Answers 2

7

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

This being a 'million ways to skin a cat' question, here's a plyr solution (using @chl's example data):

ddply(xx,.(value),summarise, wm = weighted.mean(avg,weight))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.