[R] How to avoid ifelse statement converting factor to character

Stavros Macrakis macrakis at alum.mit.edu
Thu Jun 25 23:54:01 CEST 2009


On Thu, Jun 25, 2009 at 12:47 PM, Craig P. Pyrame<crappyr at gmail.com> wrote:
> The man page Stavros quotes states that the class attribute of the result is
> taken from 'test', which clearly is not the case:

Actually, the behavior is documented pretty clearly:

     The mode of the answer will be coerced from logical to
     accommodate first any values taken from 'yes' and then
     any values taken from 'no'.

Whether this is a good design or not is another issue....  Perhaps the
justification is that it avoids evaluating the yes or no arguments (to
determine their class) in cases where their value is not needed.

Example:

     ifelse(c(T,F),1,"a") => c("1","a")

This has the same effect as

    res <- c(T,F)
    res[1] <- 1
    res[2] <- "a"

which is in fact pretty much the way it is implemented.

> And also, I find myself incapable of making sense of the "may" in "the mode
> of the result may depend on the value of 'test'" - may in what sense?

See the examples at the end of ? ifelse

         -s




More information about the R-help mailing list