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)
Related Posts
About Author:

Deepanshu founded ListenData with a simple objective - Make analytics easy to understand and follow. He has over 8 years of experience in data science. During his tenure, he has worked with global clients in various domains like Banking, Insurance, 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
Love this Post? Spread the Word!
Share