To convert factors to numeric values in R, you need to first convert the factor to a character vector and then to a numeric vector. This ensures that the factor levels are correctly transformed into their numeric equivalents.
In this example,
age_groups
which contains the values 'Young'
, 'Middle'
, 'Old'
, and 'Young'
. This vector represents different age groups.factor()
function to convert the age_groups
vector into a factor. We assign the result to a variable named age_factor
. The factor()
function automatically identifies the unique levels of the vector.age_factor
to a numeric vector using the as.numeric()
function directly on the factor. This step converts the factor levels to their corresponding numeric codes.age_numeric
.age_numeric
vector to the console to see the numeric representation of the age groups. This allows us to verify the conversion.age_groups <- c('Young', 'Middle', 'Old', 'Young')
age_factor <- factor(age_groups)
age_numeric <- as.numeric(age_factor)
print(age_numeric)
[1] 3 2 1 3
In this example,
ratings
which contains the values 'Low'
, 'Medium'
, 'High'
, 'Medium'
, and 'Low'
. This vector represents different rating levels.factor()
function to convert the ratings
vector into a factor. We assign the result to a variable named ratings_factor
. The factor()
function automatically identifies the unique levels of the vector.ratings_factor
to a numeric vector using the as.numeric()
function directly on the factor. This step converts the factor levels to their corresponding numeric codes.ratings_numeric
.ratings_numeric
vector to the console to see the numeric representation of the ratings. This allows us to verify the conversion.ratings <- c('Low', 'Medium', 'High', 'Medium', 'Low')
ratings_factor <- factor(ratings)
ratings_numeric <- as.numeric(ratings_factor)
print(ratings_numeric)
[1] 2 3 1 3 2
In this example,
satisfaction
which contains the values 'Unsatisfied'
, 'Neutral'
, 'Satisfied'
, and 'Very Satisfied'
. This vector represents different levels of customer satisfaction.factor()
function to convert the satisfaction
vector into a factor. We assign the result to a variable named satisfaction_factor
. The factor()
function automatically identifies the unique levels of the vector.as.numeric()
function on the factor itself. This assigns numeric values to each level based on their order in the factor.satisfaction_numeric
.satisfaction_numeric
vector to the console to see the numeric representation of the satisfaction levels. This allows us to verify the conversion.satisfaction <- c('Unsatisfied', 'Neutral', 'Satisfied', 'Very Satisfied')
satisfaction_factor <- factor(satisfaction, levels = c('Unsatisfied', 'Neutral', 'Satisfied', 'Very Satisfied'))
satisfaction_numeric <- as.numeric(satisfaction_factor)
print(satisfaction_numeric)
[1] 1 2 3 4
In this tutorial, we learned How to Convert Factors to Numeric in R language with well detailed examples.