[R] How to avoid ifelse statement converting factor to character
Craig P. Pyrame
crappyr at gmail.com
Fri Jun 26 15:41:18 CEST 2009
Stavros Macrakis wrote:
> It gives me a headache, too! I think you'll have to wait for a more
> expert user than me to supply explanations of these behaviors and
> their rationales.
>
Thanks, Stavros. I hope someone with expertise will shed more light on
this, and in the meantime I'll try to learn more from the manuals.
Best regards,
Craig
> -s
>
>
> On 6/26/09, Craig P. Pyrame <crappyr at gmail.com> wrote:
>
>> Stavros Macrakis wrote:
>>
>>> 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.
>>>
>>>
>> Thank you for pointing me to this. Now I get a headache from trying to
>> figure out what does mode have to do with class - I thought that the
>> class of the result should be that of test, and that the mode is
>> something entirely different. Why does coercing the mode also affect
>> the class? If the man page said "The class attribute is taken from
>> test, and it will be coerced ..." or "The mode of the result is taken
>> from test, and it will be coreced ...", would this be wrong? What is
>> the class-mode mixture about?
>>
>> Why does this fail:
>>
>> > r = as.raw(TRUE)
>> > ifelse(TRUE, r, r) => error
>>
>> This gives an error which I take for saying that raw cannot be coerced
>> to logical, but yes it can:
>>
>> > as.logical(r) => TRUE
>>
>> and raw can even be used as the condition vector in ifelse:
>>
>> > ifelse(r, 1, 2) => 1
>>
>> Best regards,
>> Craig
>>
>>
>>
>>> 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