group by in R, ddply with weighted.mean

前端 未结 2 959
天涯浪人
天涯浪人 2020-12-05 08:37

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         


        
相关标签:
2条回答
  • 2020-12-05 09:07

    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.

    0 讨论(0)
  • 2020-12-05 09:07

    Use summarise (or summarize):

    ddply(iris, "Species", summarise, 
      wmn = weighted.mean(Sepal.Length, Petal.Length),
      mn = mean(Sepal.Length))
    
    0 讨论(0)
提交回复
热议问题