[R]: z-scores for different factor levels

Joerg Maeder maeder at atmos.umnw.ethz.ch
Fri Jan 18 14:32:11 CET 2002


Stuart Leask wrote:
Hello Stuart,

i'm not sure if this is the soultion you looking for

#a random dataset with 5 factor levels
d <-
as.data.frame(cbind(BWT=runif(40),GEST=as.factor(round(runif(40)*4,0))))
#calculate mean and sd (like you didi it)
m <- tapply(d$BWT,d$GEST,mean)
s <- sqrt(tapply(d$BWT,d$GEST,var))
#recalculate BWT and save it inside your data.frame
d$BWT <- (d$BWT-m[d$GEST])/s[d$GEST]

The trick is, that you can use your GEST column to access the rigth item
of mean or sd.

gruess

joerg




> 
> Hi there.
> I am trying to generate z-scores for a variable according to it's factor
> level, leaving this result in the original dataframe.
> 
> ie. standardised birth weight for gestational age in weeks.
> BWT is birthweight
> GEST is gestational age in weeks (equivalent to the factor level)
> 
> I can generate the factor level mean & SD using tapply
> tapply(BWT,GEST,mean) etc.
> but this creates a new array of means & SDs.
> 
> - Can anyone suggest how I can slot these means & SDs by factor level
> straight back into the original dataframe, so I can then subtract the mean &
> divide by the SD to get a Z-score for each case?
> - Is there a function already available that can generate z-scores by factor
> levels?
> 
> Stuart
> 
> Dr Stuart Leask MA MRCPsych, Clinical Lecturer in Psychiatry
> University of Nottingham Dept of Psychiatry, Duncan Macmillan House
> Porchester Road, Nottingham. NG3 6AA. UK
> http://www.nottingham.ac.uk/psychiatry/staff/sjl.html
> 
> -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
> 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
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

-- 
    Joerg Maeder             IACETH              INSTITUTE
   PhD Student                              FOR ATMOSPHERIC 
  Phone: +41 1 633 36 25                 AND CLIMATE SCIENCE
 Fax: +41 1 633 10 58                  ETH ZÜRICH Switzerland
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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