[R] Two-argument functions in tapply()
Peter Dalgaard BSA
p.dalgaard at biostat.ku.dk
Thu Mar 22 16:04:53 CET 2001
"Michal Bojanowski" <buoy at wp.pl> writes:
> I wanted to compute a means of X weighted by W within groups defined by F
> with the function below:
>
> wmean <- function(x,w)
> {
> wm <- sum( x*w/sum(w) )
> wm
> }
(Now whatever was wrong with weighted.mean()??)
> used within tapply() function, like:
>
> tapply(x,f,wmean,w=w)
>
> but I received some values with 2 warnings:
>
> 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
>
> What is the right way to get the results (how to use 2-argument function in
> tapply()), or maybe there is another simple way to do this
A couple of ways, none really pretty:
c(by(dataframe,f, function(d) evalq(wmean(x,w), d)))
or equivalently
c(by(dataframe,f, eval, expr=quote(wmean(x,w))))
or more directly
ind<-seq(along=x)
tapply(ind, f, function(i) wmean(x[i],w[i]))
And of course
tapply(x*w, f, sum) / tapply(w, f, sum)
--
O__ ---- Peter Dalgaard Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics 2200 Cph. N
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list