[R] help with tapply and weighted.mean
Frank E Harrell Jr
fharrell at virginia.edu
Mon Aug 4 03:08:46 CEST 2003
On Thu, 31 Jul 2003 22:00:13 +0400
Kosenkov Kirill <Kosenkov.Kirill at nac.spb.ru> wrote:
> Hello!
>
> I have data frame with 'weights' in one of the columns. I need to
> compute weighted mean on another column other factor variable and
> i am trying to:
>
> res<-tapply(data$k,list(data$model),weighted.mean,w=data$w,na.rm=T)
>
> and i get:
>
> Warning messages:
> 1: longer object length
> is not a multiple of shorter object length in: x * w
> 2: longer object length
> is not a multiple of shorter object length in: x * w
> 3: longer object length
> is not a multiple of shorter object length in: x * w
> 4: longer object length
> is not a multiple of shorter object length in: x * w
> 5: longer object length
> is not a multiple of shorter object length in: x * w
> 6: longer object length
> is not a multiple of shorter object length in: x * w
> 7: longer object length
> is not a multiple of shorter object length in: x * w
> 8: longer object length
> ....
>
> What i am doing wrong? How i can pass vector of weights to the
> 'weighted.mean' when using 'tapply'?
>
> Thanks!
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
Here's an alternative that works.
install.packages('Hmisc')
library(Hmisc)
g <- function(y) wtd.mean(y[,1],y[,2])
summarize(cbind(y, wts), llist(stratvar1,stratvar2), g, stat.name='y')
llist is like list except it remembers the names of the arguments. wtd.mean, llist, and summarize are in Hmisc.
---
Frank E Harrell Jr Prof. of Biostatistics & Statistics
Div. of Biostatistics & Epidem. Dept. of Health Evaluation Sciences
U. Virginia School of Medicine http://hesweb1.med.virginia.edu/biostat
More information about the R-help
mailing list