s-news
[Top] [All Lists]

[S] tapply(X, INDICES, FUN,Y) if Y needs indices too - Summary

To: "'S news'" <s-news@wubios.wustl.edu>
Subject: [S] tapply(X, INDICES, FUN,Y) if Y needs indices too - Summary
From: John Thaden <jjthaden@flash.net>
Date: Sat, 23 Oct 1999 10:29:56 -0500
Sender: owner-s-news@wubios.wustl.edu
Thank you Alan Zaslavsky and Pat Burns for suggesting general ways to apply
a function to strata if the function needs more than one stratified
argument, and to Charles C. Berry for a specific solution to my example
with weighted.mean.  All of these work.  My question:

> . . . I'd like to use tapply (or any function) to get a weighted mean
> for each stratum of X
>   >tapply(X, strata, weighted.mean, w = weights)
>where weights is a vector of equal length as X and strata.
>This generates incorrect weighted means and a slew of warnings . . .
>
>In S-Plus 4.5 for Windows, is there a vectorized way to apply to the strata
>of a dataset a function like weighted.mean that asks for more than one
>stratified argument?

The replies:
###### Alan Zaslavsky <zaslavsk@hcp.med.harvard.edu>
some people have suggested something like the following:
tapply(1:length(X),strata,
        function(indices,x,ww) weighted.mean(y=x[indices],w=ww[indices]),
        x=X,ww=w)
which looks kinda ridiculous to me, but they say it is still much faster 
than looping.

######From: Pat Burns <pburns@pburns.seanet.com>
You can use the trick using lapply that is on pages 78-79 of S Poetry.
Basically you want to loop over the unique strata and write a function
that selects x and weights from the stratum and then does the mean.
http://www.seanet.com/~pburns/Spoetry
http://www.i-way.co.uk/~pat/Spoetry

#####From: "Charles C. Berry" <cberry@tajo.ucsd.edu>
Off the top of my head (caveat ...):
wt.mean <- tapply(X*weights,stratum,sum)/tapply(weights,stratum,sum)


************************************************************
John J. Thaden, Ph.D., Instructor        jjthaden@life.uams.edu
Department of Geriatrics                     (501) 257-5583
University of Arkansas for Medical Sciences  FAX: (501) 257-4822
      mail & ship to:   J. L. McClellan V.A. Medical Center
                Research-151 (Room GB103 or GC124)
                4300 West 7th Street
                Little Rock AR 72205 USA
***********************************************************
-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu.  To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message:  unsubscribe s-news

<Prev in Thread] Current Thread [Next in Thread>
  • [S] tapply(X, INDICES, FUN,Y) if Y needs indices too - Summary, John Thaden <=