[R] Calculate weighted mean for each group

2009-07-23 Thread Alexis Maluendas
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

Re: [R] Calculate weighted mean for each group

2009-07-23 Thread milton ruser
try your first reproducible line first :-) On Thu, Jul 23, 2009 at 5:18 PM, Alexis Maluendas avmaluend...@gmail.comwrote: Hi R experts, I need know how calculate a weighted mean by group in a data frame. I have tried with aggragate() function:

Re: [R] Calculate weighted mean for each group

2009-07-23 Thread Chuck Cleland
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)

Re: [R] Calculate weighted mean for each group

2009-07-23 Thread Marc Schwartz
On Jul 23, 2009, at 4: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

Re: [R] Calculate weighted mean for each group

2009-07-23 Thread David Freedman
After you fix your data frame and if you don't using 2 packages, you might try something like: lib(plyr) #for 'by' processing lib(Hmisc) # for its wtd.mean function d=data.frame(x=c(15,12,3,10,10),g=c(1,1,2,2,3),w=c(2,1,5,2,5)) ; d ddply(d,~g,function(df) wtd.mean(df$x,df$w)) milton ruser