[R] Revert a factor to its numeric values

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Aug 18 11:00:56 CEST 2004


On Wed, 18 Aug 2004, Göran Broström wrote:

> On Wed, Aug 18, 2004 at 09:30:50AM +0100, Prof Brian Ripley wrote:
> > 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").
> 
> Didn't work either. :-)
> 
> I really want the underlying numeric codes (convert the variable to numeric).
> 'as.integer(x)' seems to do the trick, is that correct? Also 'as.numeric(x)', although it is "meaningless" according to the help page.

as.integer is OK, but unclass() is the usual way (it doesn't lose the 
other attributes such as names).

x <- factor(1:10)
names(x) <- letters[1:10]
> as.integer(x)
 [1]  1  2  3  4  5  6  7  8  9 10
> unclass(x)
 a  b  c  d  e  f  g  h  i  j
 1  2  3  4  5  6  7  8  9 10
attr(,"levels")
 [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10"


> > > 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.
> 
> Thanks; exactly what I was looking for.

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