[R] Revert a factor to its numeric values
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Wed Aug 18 11:57:38 CEST 2004
gb at stat.umu.se (Göran Broström) writes:
> 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
>
> Also,
>
> > as.numeric(as.character(x))
> [1] NA NA NA NA
> Warning message:
> NAs introduced by coercion
>
> What am I doing wrong? This is R-1.9.1, Linux (debian installation)
You appear to be assuming tha R knows how to make numbers from text
strings
as.numeric(c("jedan","dva","tri","ceteri"))
is not going to give you 1,2,3,4 either (not even in a Croatian
locale).
The suggestion on the help page works for numeric levels:
> x <- c(1, 2, 1, 2)
> x <- factor(x, labels = c("5", "7"))
> as.numeric(levels(x))[x]
[1] 5 7 5 7
> Another question: I have a factor with four levels, which I want
> to collapse to two. How do I do it in the simplest possible way?
> x <- factor(c("jedan","dva","tri","ceteri"))
> x
[1] jedan dva tri ceteri
Levels: ceteri dva jedan tri
> levels(x) <- c("even","even","odd","odd")
> x
[1] odd even odd even
Levels: even odd
--
O__ ---- Peter Dalgaard Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics 2200 Cph. N
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-help
mailing list