How to convert factor format to numeric format in R without changing the values?


This question already has an answer here:


Replace comma's with dots, which represent decimals in R. Otherwise R thinks it is a character and coerces the value to NA.

Then, to extract values:


(thanks @SimonO101 for the correction)

Try this to replace the comma in your data:

fac<- c( "0" , "0" , "1,5" , "0" , "0" , "8" )
#[1] "0"   "0"   "1,5" "0"   "0"   "8" 
fac <- as.numeric( sub(",", ".", fac) )
#[1] 0.0 0.0 1.5 0.0 0.0 8.0

More generally converting factors to their underlying values rather than the factor representation:

fac <- as.factor( fac )
#[1] 1 1 2 1 1 3
#[1] 0.0 0.0 1.5 0.0 0.0 8.0

However, this is the canonical way of transforming to original values


From the help page ?as.factor

In particular, as.numeric applied to a factor is meaningless, and may happen by implicit coercion. To transform a factor f to approximately its original numeric values, as.numeric(levels(f))[f] is recommended and slightly more efficient than as.numeric(as.character(f)).

Need Your Help

how to catch the value of dialpads pressed button?

android call sip

I am developing a SIP application for making and receiving a call. For that purpose I did analysis on open source project SipDroid. in that project how they catch the value of dialpads pressed button