[R] convert factor to numeric

Philipp Pagel p.pagel at gsf.de
Wed Jun 4 14:04:46 CEST 2003


	Hi R-experts!

Every once in a while I need to convert a factor to a vector of numeric
values. as.numeric(myfactor) of course returns a nice numeric vector of
the indexes of the levels which is usually not what I had in mind:

> v <- c(25, 3.78, 16.5, 37, 109)
> f <- factor(v)
> f
[1] 25   3.78 16.5 37   109
Levels: 3.78 16.5 25 37 109
> as.numeric(f)
[1] 3 1 2 4 5
>

What I really want is a function "unfactor" that returns v:
> unfactor(f)
[1]  25.00   3.78  16.50  37.00 109.00

Of course I could use something like

> as.numeric(levels(f)[as.integer(f)])

But I just can't believe there is no R function to do this in a more
readable way. Actually, the behaviour of as.numeric() doesn't strike me
as very intuitive. I'm sure it has been implemented that way for a
reason - but what is it?

cu
	Philipp

-- 
Dr. Philipp Pagel                                Tel.  +49-89-3187-3675
Institute for Bioinformatics / MIPS              Fax.  +49-89-3187-3585
GSF - National Research Center for Environment and Health
Ingolstaedter Landstrasse 1
85764 Neuherberg
Germany




More information about the R-help mailing list