How to summarise data by group with weighted mean?

匿名 (未验证) 提交于 2019-12-03 08:44:33

问题:

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.

回答1:

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


回答2:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!