[R] converting factor to numeric

Thomas W Blackwell tblackw at umich.edu
Fri Aug 22 04:17:02 CEST 2003


Kjetil  -

EdadC seems to have only five levels, anyway.  What are those
five levels ?  Are they strings which it would make sense to
interpret as numeric ?  as.numeric() obviously thinks they
are not.

-  tom blackwell  -  u michigan medical school  -  ann arbor  -

On Thu, 21 Aug 2003, kjetil brinchmann halvorsen wrote:

> 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