[R] Revert a factor to its numeric values

Göran Broström gb at stat.umu.se
Wed Aug 18 16:51:30 CEST 2004


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.

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

Göran




More information about the R-help mailing list