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

Mohinder Datta mohinder_datta at yahoo.com
Thu Apr 9 16:39:20 CEST 2009


Thank you for your help!


--- On Thu, 4/9/09, Thomas Lumley <tlumley at u.washington.edu> wrote:

> From: Thomas Lumley <tlumley at u.washington.edu>
> Subject: Re: [R] better way of recoding factors in data frame?
> To: mohinder_datta at yahoo.com
> Cc: r-help at r-project.org
> Date: Thursday, April 9, 2009, 2:10 PM
> 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