Here are two ways:
f1 <- function(i) weighted.mean(X[i,1], X[i,2])
aggregate(list(wmean = 1:nrow(X)), as.data.frame(X[,3:5]), f1)
f2 <- function(x) data.frame(wmean = weighted.mean(x[,1], x[,2]), x[1, 3:5])
do.call(rbind, by(X, as.data.frame(X[,3:5]), f2))
Also you check out the na.rm= argument
You can do it directly from the X matrix like so:
> by(X, as.list(as.data.frame(X[,3:5])), function(R)weighted.mean(R
[1], R[2]))
A: 0
B: 0
C: 0
[1] 0.4912458
A: 1
B: 0
C: 0
[1] NA
-
HI,
I am trying to figure out an efficient way to calculate group means and
associate each entry with it. I made up an example:
A = rep(rep(0:1,each=2),3)
B = rep(rep(0:1,4),3)
C = rep(rep(c(0,0,1,1),2),3)
X =cbind(rnorm(24,0,1),runif(24,0,1),A,B,C)
A