[R] converting factor to numeric

kjetil brinchmann halvorsen kjetil at entelnet.bo
Fri Aug 22 02:40:28 CEST 2003


Hola!

The R FAQ says: 

7.12 How do I convert factors to numeric?

It may happen that when reading numeric data into R (usually, when 
reading in a file), they come in as factors. If f is such a factor 
object, you can use

as.numeric(as.character(f))

to get the numbers back. More efficient, but harder to remember, is

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

In any case, do not call as.numeric() or their likes directly. 

But trying to follow the advice:

(this is without package method attached, but the results are the 
same with):

First doing as one shouldn't:

> table( as.numeric(EdadC) )

  1   2   3   4   5 
 20  99 157 127  74 

Doing as the FAQ says:

> table( as.numeric(as.character(EdadC)) )
character(0)
Warning message: 
NAs introduced by coercion 

or:

> table( as.numeric(levels(EdadC))[as.integer(EdadC)] )
character(0)
Warning message: 
NAs introduced by coercion 

?

Kjetil Halvorsen




More information about the R-help mailing list