On 7/23/2009 5:18 PM, Alexis Maluendas wrote:
> Hi R experts,
> 
> I need know how calculate a weighted mean by group in a data frame. I have
> tried with aggragate() function:
> 
> data.frame(x=c(15,12,3,10,10),g=c(1,1,1,2,2,3,3),w=c(2,3,1,5,5,2,5)) -> d
> aggregate(d$x,by=list(d$g),weighted.mean,w=d$w)
> 
> Generating the following error:
> 
> Error en FUN(X[[1L]], ...) : 'x' and 'w' must have the same length

DF <- data.frame(x=c(15,12, 3,10,10,14,12),
                 g=c( 1, 1, 1, 2, 2, 3, 3),
                 w=c( 2, 3, 1, 5, 5, 2, 5))

sapply(split(DF, DF$g), function(x){weighted.mean(x$x, x$w)})
       1        2        3
11.50000 10.00000 12.57143

> Thanks in advance
> 
>       [[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help@r-project.org 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. 

-- 
Chuck Cleland, Ph.D.
NDRI, Inc. (www.ndri.org)
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894

______________________________________________
R-help@r-project.org 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.

Reply via email to