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