[R] find weighted group mean

Alex Brown alex at transitive.com
Tue Oct 10 17:59:32 CEST 2006


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
--------------------------------------------------------------------
A: 0
B: 1
C: 0
[1] -0.2694550
--------------------------------------------------------------------
A: 1
B: 1
C: 0
[1] NA
--------------------------------------------------------------------
A: 0
B: 0
C: 1
[1] NA
--------------------------------------------------------------------
A: 1
B: 0
C: 1
[1] 0.01102718
--------------------------------------------------------------------
A: 0
B: 1
C: 1
[1] NA
--------------------------------------------------------------------
A: 1
B: 1
C: 1
[1] -0.5622041


Or you can poke about a bit with it first:

 > Z = as.data.frame(X)
 > names(Z) = c("x", "w", "A", "B", "C")
 > by(Z[,c("x", "w")], list(paste("A", Z$A, "B", Z$B, "C", Z$C)),  
function(R)weighted.mean(R$x, R$w))
: A 0 B 0 C 0
[1] 0.4912458
--------------------------------------------------------------------
: A 0 B 1 C 0
[1] -0.2694550
--------------------------------------------------------------------
: A 1 B 0 C 1
[1] 0.01102718
--------------------------------------------------------------------
: A 1 B 1 C 1
[1] -0.5622041

-Alex

On 10 Oct 2006, at 16:13, Young Cho 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