[R] better way of recoding factors in data frame?

Thomas Lumley tlumley at u.washington.edu
Thu Apr 9 16:10:04 CEST 2009


On Thu, 9 Apr 2009 mohinder_datta at yahoo.com wrote:

>
> Hi all,
>
> I apologize in advance for the length of this post, but I wanted to make sure 
> I was clear.

Good strategy.


>I tried this:
>
>> myFrame2$newSex <- ifelse(myFrame2$newSex ==1 || myFrame2$newSex == 2, myFrame2$newSex, 0)
>

First, you need |, not ||, because || returns just a single value.

This still won't quite work, because the condition will be NA when newSex is NA (if you don't know a number then you don't know whether it is equal to 1 or 2).

So,
myFrame2$newSex <- ifelse(myFrame2$newSex %in% c(1,2), myFrame2$newSex, 0)

or, slightly shorter
myFrame2$newSex <- with(myFrame2, ifelse(newSex %in% c(1,2), newSex, 0)

     -thomas

Thomas Lumley			Assoc. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle




More information about the R-help mailing list