[R] strange behavior of ifelse with factors

ivo welch ivo.welch at gmail.com
Fri Aug 20 23:38:28 CEST 2010


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)



More information about the R-help mailing list