[R] Condition to factor (easy to remember)

David Winsemius dwinsemius at comcast.net
Wed Sep 30 14:21:51 CEST 2009


On Sep 30, 2009, at 3:43 AM, Dieter Menne 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)

I agree with your observation that many people express a preference  
for the ifelse version. I had the same sort of comment on some of my  
Excel code (not in a statistical application)  a couple of days ago.  
In your code the as.integer function is superfluous and you could  
argue that it might even be easier to understand for the Boolean- 
challenged masses if you substituted as.logical(). It would be also  
superfluous, but it might convey a message that the programmer _knew+  
that the "+" operation is capable of doing the necessary coercion.

>
> # Easiest to understand
> factor(ifelse(data <=10, levs[1], levs[2]), levels=levs)
>
> -- 
-- Boole Rules

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list