[R] Assigning factor to character vector

Milan Bouchet-Valat nalimilan at club.fr
Sat Apr 20 14:49:54 CEST 2013


Hi!

Yesterday I accidentally discovered this:
> a <- LETTERS[1:5]
> a
[1] "A" "B" "C" "D" "E"
> 
> a[1] <- factor(a[1])
> a
[1] "1" "B" "C" "D" "E"

BUT:
> b <- factor(LETTERS[1:5])
> b
[1] A B C D E
Levels: A B C D E
> b[1] <- factor(b[1])
> b
[1] A B C D E
Levels: A B C D E
> b[1] <- as.character(b[1])
> b
[1] A B C D E
Levels: A B C D E

I think this would definitely deserve a mention in the R Inferno...

I guess this is documented somewhere (though I could not find anything
in help("[<-"). Would someone be kind enough to give me the explanation
of this behavior? I suspect this has something to do with the coercion
order, but I do not really get why a[1] does not get assigned the result
of as.character(factor(a[1]))... Probably, there is no special-casing of
factors, which are handled as integer vectors?

Wouldn't it be useful to print a warning when this happens, since nobody
reasonable would rely on such a special behavior? I wish R had a "safe
mode" where all these tricky implicit coercion cases would warn... :-/


Regards



More information about the R-help mailing list