I am trying to do a \"group by\" - style weighted mean in R. With some basic mean the following code (using the plyr package from Hadley) worked well.
ddply
Use an anonymous function:
> ddply(iris,"Species",function(X) data.frame(wmn=weighted.mean(X$Sepal.Length,
+ X$Petal.Length),
+ mn=mean(X$Sepal.Length)))
Species wmn mn
1 setosa 5.016963 5.006
2 versicolor 5.978075 5.936
3 virginica 6.641535 6.588
>
This computes a weighted mean of Sepal.Length (weighted by Petal.Length) as well as unweighted mean and returns both.
Use summarise (or summarize):
ddply(iris, "Species", summarise,
wmn = weighted.mean(Sepal.Length, Petal.Length),
mn = mean(Sepal.Length))