[R] Revert a factor to its numeric values

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Aug 18 10:30:50 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
>  
> 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)

Your factor is made up of "one", "two", which are not numeric -- don't
expect R to speak English (or Swedish).  You could just as easily have
used labels = c("apples", "oranges").

> 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?

via levels<- : there is an example on the help page for levels.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list