How to summarize group data with a weighted average?

FROM

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 be the same length

But

weighted.mean(x$avg,w=x$weight);

works great.

+6
source share
2 answers

As shown in the old thread of R , you can use by instead of:

 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)) 
+7
source

This is a question about β€œmillions of ways to infect a cat”, here is the plyr solution (using the data from the @chl example):

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

Source: https://habr.com/ru/post/895572/


All Articles