[R] Two-argument functions in tapply()
Rashid Nassar
rnassar at duke.edu
Thu Mar 22 17:42:36 CET 2001
Just be careful using weighted.means() within tapply(), as the result may
not be what one might expect (I think because of the recycling rule, if I
remember correctly) if one hasn't thought it through. (I should think the
same may apply also to aggregate() ).
Rashid Nassar
On 22 Mar 2001, Peter Dalgaard BSA wrote:
> Date: 22 Mar 2001 16:04:53 +0100
> From: Peter Dalgaard BSA <p.dalgaard at biostat.ku.dk>
> To: Michal Bojanowski <buoy at wp.pl>
> Cc: R-project Mailing List <r-help at stat.math.ethz.ch>
> Subject: Re: [R] Two-argument functions in tapply()
>
> "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
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
>
>
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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