Weighted mean with by function

后端 未结 3 671
情歌与酒
情歌与酒 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:04

    You need to pass the weights along with the values to be averaged in by():

    by(df[c("A","C")], df$B, function(x) weighted.mean(x$A, x$C))
    # df$B: gb
    # [1] 4
    # ------------------------------------------------------------ 
    # df$B: hi
    # [1] 25.44444
    # ------------------------------------------------------------ 
    # df$B: yo
    # [1] 3
    

提交回复
热议问题