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

<>

This question already has an answer here:

Answers


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:

as.numeric(levels(df1[,2])[df[,2]])

(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 )
as.numeric(fac)
#[1] 1 1 2 1 1 3
as.numeric(as.character(fac))
#[1] 0.0 0.0 1.5 0.0 0.0 8.0

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

 as.numeric(levels(fac))[fac]

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

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.