Skip to content

Changing factor to numeric

7 messages · ojal john owino, Uwe Ligges, Krzysztof Sakrejda +4 more

#
From ?factor:

The interpretation of a factor depends on both the codes and the 
"levels" attribute. Be careful only to compare factors with the same set 
of levels (in the same order). In particular, as.numeric applied to a 
factor is meaningless, and may happen by implicit coercion. To transform 
a factor f to its original numeric values, as.numeric(levels(f))[f] is 
recommended and slightly more efficient than as.numeric(as.character(f)).

Uwe Ligges
ojal john owino wrote:
#
If the real problem is that R reads your data file and converts 
everything it can into factors try including stringsAsFactors=FALSE
in your read.table (or similar) statement.  I run into this often enough 
that I set it as an option (I think it's: 
options(stringsAsFactors=FALSE).  Then you can do the conversion as 
needed.  Using as.numeric(as.character(f)) often changes values (due to 
the whole factor/levels business).

... I also seem to remember read.table will let you pre-specify the data 
type of each column.

Krzysztof
Uwe Ligges wrote:

  
    
#
Try:

as.numeric(as.character(x))

I usually define the following for this purpose:
factor.to.number=function(x){
as.numeric(as.character(x))
}


On Tue, Mar 10, 2009 at 2:25 AM, ojal john owino
<ojal.johnowino at googlemail.com> wrote:

  
    
#
If you don't need any factors use read.csv(...whatever..., as.is = TRUE)
and then as.numeric will work.

On Tue, Mar 10, 2009 at 1:25 AM, ojal john owino
<ojal.johnowino at googlemail.com> wrote: