开发者

How to summarise data by group with weighted mean?

开发者 https://www.devze.com 2023-03-29 23:32 出处:网络
Wit开发者_如何学Ch xa=aggregate(x$avg,by=list(x$value),FUN=weighted.mean,w=x$weight) gives me an error

Wit开发者_如何学Ch

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.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消