[R] strange behavior of ifelse with factors

Patrick Burns pburns at pburns.seanet.com
Sat Aug 21 10:14:44 CEST 2010


This is mentioned on page 70 of 'The R Inferno'.

On 20/08/2010 22:38, ivo welch wrote:
> Dear R experts:  this is probably correct behavior, but I do want to
> point out that it is unexpected to someone not too well versed:
>
>> test=factor("A","B","C","A")
>> ifelse(test=="A", as.factor("A"), test)
> [1] 1 2 3 1
>
> ok, my factor was just coerced into integers, even though I have a
> logical vector as my condition and factors as my true and false
> values.  this means that
>
>> test[1:3]=ifelse(test[1:3]=="A", rep(as.factor("A"),3), test[1:3])
>
> won't work.  I do know how to program around this, but since it
> stumped me for a while (in a more complex program, of course), I
> thought I would drop this note.
>
> regards,
>
> /iaw
> ----
> Ivo Welch (ivo.welch at brown.edu, ivo.welch at gmail.com)
>
> ______________________________________________
> 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.
>

-- 
Patrick Burns
pburns at pburns.seanet.com
http://www.burns-stat.com
(home of 'Some hints for the R beginner'
and 'The R Inferno')



More information about the R-help mailing list