[R] Ifelse statement on a factor level data frame

William Dunlap wdunlap at tibco.com
Sun Sep 28 19:24:39 CEST 2014

ifelse() often has problems constructing the right type of return value.

if you want to keep the data as a factor (with its existing levels)
use x[condition] <- value instead of ifelse(condition, value, x).  E.g.,
   > x <- factor(c("Large","Small","Small","XLarge"),
   > x
   [1] Large  Small  Small  XLarge
   Levels: Small Med Large XLarge
   > XLarge2Large <- function(x) { x[x=="XLarge"] <- "Large" ; x }
   > XLarge2Large(x)
   [1] Large Small Small Large
   Levels: Small Med Large XLarge
instead of things like
   > ifelse(x=="XLarge", "Large", x)
   [1] "3"     "1"     "1"     "Large"

If you don't care about the factor levels, then convert x to a character vector.

Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Sat, Sep 27, 2014 at 10:13 PM, Jeff Newmiller
<jdnewmil at dcn.davis.ca.us> wrote:
> Not reproducible, ball in your court. However, in the meantime, my suggestion is to not do that. Convert to character before you alter the factor, then convert back when you are done.
> ---------------------------------------------------------------------------
> Jeff Newmiller                        The     .....       .....  Go Live...
> DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
>                                       Live:   OO#.. Dead: OO#..  Playing
> Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
> /Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
> ---------------------------------------------------------------------------
> Sent from my phone. Please excuse my brevity.
> On September 27, 2014 9:49:41 PM PDT, Kate Ignatius <kate.ignatius at gmail.com> wrote:
>>Quick question:
>>I am running the following code on some variables that are factors:
>>dbpmn$IID1new <- ifelse(as.character(dbpmn[,2]) ==
>>as.character(dbpmn[,(21)]), dbpmn[,20], '')
>>Instead of returning some value it gives me this:
>>c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1))
>>Playing around with the code, gives me some kind of variation to it.
>>Is there some way to get me what I want.  The variable that its
>>suppose to give back is a bunch of sampleIDs.
>>R-help at r-project.org mailing list
>>PLEASE do read the posting guide
>>and provide commented, minimal, self-contained, reproducible code.
> ______________________________________________
> R-help at 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.

More information about the R-help mailing list