R : Converting a factor to integer

Deepanshu Bhalla 1 Comment

This post explains how to convert a factor to integer in R, along with examples. Most of R Programmers make mistake while converting a factor variable to integer.

Why to Convert a factor to integer in R?
  1. Statistical Analysis: Some statistical analysis functions or algorithms require numeric input. Converting categorical data represented as factors to integers might be necessary for these analyses.
  2. Plotting and Visualization: Some plots and visualization functions require numeric values.
  3. Efficiency: For large datasets, using integers instead of factors can improve memory usage and computation speed.
Let's create a factor variable
a <- factor(c(2, 4, 3, 3, 4))
str(a)
Incorrect Way
a1 = as.integer(a)
str(a1)
Output
[1] 1 3 2 2 3

as.integer() returns a vector of the levels of your factor and not the original values.

Correct Way
a2 = as.integer(as.character(a))
str(a2)
Output
[1] 2 4 3 3 4
Related Posts
Spread the Word!
Share
About Author:
Deepanshu Bhalla

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 worked with global clients in various domains like Banking, Insurance, Private Equity, Telecom and HR.

Post Comment 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