[R] find weighted group mean
Gabor Grothendieck
ggrothendieck at gmail.com
Tue Oct 10 18:10:27 CEST 2006
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 in ?weighted.mean which
may or may not be relevant to you.
On 10/10/06, Young Cho <young.stat at gmail.com> wrote:
> 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 B C
> [1,] -1.92926469 0.32213127 0 0 0
> [2,] -0.83935617 0.77794096 0 1 0
> [3,] -1.27799751 0.26276934 1 0 1
>
> Suppose I want to compute a weighted mean of X[,1] by for each group, which
> is defined by unique vector (A,B,C) with weights are X[,2]. And then add a
> column for the weighted group mean. How can I do this ? My matrix is fairly
> large (few thousands) but, luckily, I have only a few factors (<10).
>
> Thanks a lot,
>
> Young.
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list