Weighted mean with by function

后端 未结 3 707
情歌与酒
情歌与酒 2021-01-21 21:45

Trying to get weighted mean for a couple of categories want to use by(df$A,df$B,function(x) weighted.mean(x,df$C)) This doesn\'t work of course. Is there a way to do this using

3条回答
  •  日久生厌
    2021-01-21 22:20

    Or simply recreate the calculation used by weighted.mean():

    by(df,df$B,function(df)with(df,sum(A*C)/sum(C)))
    
    df$B: gb
    [1] 4
    ------------------------------------------------------------ 
    df$B: hi
    [1] 25.44444
    ------------------------------------------------------------ 
    df$B: yo
    [1] 3
    

提交回复
热议问题