> -----Original Message-----
> From: r-help-boun...@r-project.org 
> [mailto:r-help-boun...@r-project.org] On Behalf Of Douglas Bates
> Sent: Wednesday, September 30, 2009 12:42 PM
> To: Dieter Menne
> Cc: r-help@r-project.org
> Subject: Re: [R] Condition to factor (easy to remember)
> 
> On Wed, Sep 30, 2009 at 2:43 AM, Dieter Menne
> <dieter.me...@menne-biomed.de> wrote:
> 
> > Dear List,
> 
> > creating factors in a given non-default orders is 
> notoriously difficult to
> > explain in a course. Students love the ifelse construct 
> given below most,
> > but I remember some comment from Martin Mächler (?) that 
> ifelse should be
> > banned from courses.
> 
> > Any better idea? Not necessarily short, easy to remember is 
> important.
> 
> > Dieter
> 
> > data = c(1,7,10,50,70)
> > levs = c("Pre","Post")
> >
> > # Typical C-Programmer style
> > factor(levs[as.integer(data >10)+1], levels=levs)
> >
> > # Easiest to understand
> > factor(ifelse(data <=10, levs[1], levs[2]), levels=levs)
> 
> Why not
> 
> > factor(data > 10, labels = c("Pre", "Post"))
> [1] Pre  Pre  Pre  Post Post
> Levels: Pre Post
> 
> All you have to remember is that FALSE comes before TRUE.

And if you don't  want to remember that order or if you want TRUE to come
before FALSE use the levels argument to factor.  E.g.,
    > factor(data>10, levels=c(TRUE,FALSE), labels=c("Post","Pre"))
    [1] Pre  Pre  Pre  Post Post
    Levels: Post Pre

Bill Dunlap
TIBCO Software Inc - Spotfire Division
wdunlap tibco.com 

> 
> ______________________________________________
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
> 

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to