R : Converting a factor to integer

Most of R Programmers make mistake while converting a factor variable to integer.

Let's create a factor variable
a <- factor(c(2, 4, 3, 3, 4))
str(a)
Incorrect Way
a1 = as.numeric(a)
str(a1)
as. numeric() returns a vector of the levels of your factor and not the original values.

Correct Way
a2 = as.numeric(as.character(a))
str(a2)
Spread the Word!
Share
Related Posts
About Author:

Deepanshu founded ListenData with a simple objective - Make analytics easy to understand and follow. He has over 10 years of experience in data science. During his tenure, he has worked with global clients in various domains like Banking, Insurance, Private Equity, Telecom and Human Resource.

1 Response to "R : Converting a factor to integer"
  1. Could you explain more about why you need to do this? Sort of a basic question, but would be helpful for us less experienced R users.

    ReplyDelete

Next → ← Prev

Looks like you are using an ad blocker!

To continue reading you need to turnoff adblocker and refresh the page. We rely on advertising to help fund our site. Please whitelist us if you enjoy our content.