[R] Revert a factor to its numeric values
Thomas Lumley
tlumley at u.washington.edu
Wed Aug 18 17:51:11 CEST 2004
On Wed, 18 Aug 2004, Göran Broström wrote:
> I'm trying a recommendation on the help page for 'factor':
>
> > x <- c(1, 2, 1, 2)
> > x <- factor(x, labels = c("one", "two"))
> > x
> [1] one two one two
> Levels: one two
> > as.numeric(levels(x))[x]
> [1] NA NA NA NA
> Warning message:
> NAs introduced by coercion
>
usually when people want to "revert a factor to its numeric values" they
mean that the labels are numbers and they want those numbers. In that
case as.numeric(x) or unclass(x) are wrong because they give you the
underlying codes. You, somewhat unusually, actually want the underlying
codes, which you get with unclass(x).
-thomas
More information about the R-help
mailing list