The documentation for factors gives this code as its first example of constructing a factor variable:
(ff <- factor(substring("statistics", 1:10, 1:10), levels = letters))
Said documentation suggests the following:
To transform a factor
fto approximately its original numeric values,as.numeric(levels(f))[f]is recommended and slightly more efficient thanas.numeric(as.character(f)).
But when I try those on their example, I get nonsense:
> (ff <- factor(substring("statistics", 1:10, 1:10), levels = letters))
[1] s t a t i s t i c s
Levels: a b c d e f g h i j k l m n o p q r s t u v w x y z
> ff
[1] s t a t i s t i c s
Levels: a b c d e f g h i j k l m n o p q r s t u v w x y z
> as.numeric(levels(ff))[ff]
[1] NA NA NA NA NA NA NA NA NA NA
Warning message:
NAs introduced by coercion
> as.numeric(as.character(ff))
[1] NA NA NA NA NA NA NA NA NA NA
Warning message:
NAs introduced by coercion
Where is my misunderstanding? I see nothing abnormal about the ff factor variable. It definitely has underlying numbers:
> as.integer(ff)
[1] 19 20 1 20 9 19 20 9 3 19
and although its levels are characters, I don't see anything strange about that either - factor variables always have levels that are characters.