The levels() function in R is “used to provide access to the levels attribute”. The first form returns the value of the levels of its argument, and the second sets the attribute. You can assign the individual levels using the gl() function.
Syntax
levels(x)
levels(x) <- value
Parameters
- x: It is the x is an input factor.
- value: It is a valid value for levels(x). For the default method, NULL or a character vector. For the factor method, a vector of character strings with a length of at least the number of levels of x or a named list specifying how to rename the levels.
Example 1
data_vector <- c("Hermione", "Harry", "Ron", "Albus")
factor_vector <- factor(data_vector)
factor_vector
data <- factor_vector[1]
data
Output
[1] Hermione Harry Ron Albus
Levels: Albus Harry Hermione Ron
[1] Hermione
Levels: Albus Harry Hermione Ron
In this example, we have not defined any levels, so it takes the levels from the data.
Example 2
We can assign the new levels using the levels() function.
data_vector <- c("Hermione", "Harry", "Ron", "Draco")
factor_vector <- factor(data_vector)
factor_vector
levels(factor_vector) <- c("Godric", "Salazar", "Hufflepuff", "Ravenclaw")
factor_vector
Output
[1] Hermione Harry Ron Draco
Levels: Draco Harry Hermione Ron
[1] Hufflepuff Salazar Ravenclaw Godric
Levels: Godric Salazar Hufflepuff Ravenclaw
Example 3
You can summarize the vector using the summary() method.
data_vector <- c("Hermione", "Harry", "Ron", "Draco")
factor_vector <- factor(data_vector)
factor_vector
levels(factor_vector) <- c("Godric", "Salazar", "Hufflepuff", "Ravenclaw")
summary(factor_vector)
Output
[1] Hermione Harry Ron Draco
Levels: Draco Harry Hermione Ron
Godric Salazar Hufflepuff Ravenclaw
1 1 1 1
View the levels of a factor variable
levels(main_factor_variable)
Change the levels of a factor variable
levels(main_factor_variable) <- c("new_level1", "new_level2", ...)
Reorder the levels of a factor variable
main_factor_variable <- factor(main_factor_variable,
levels = c("new_level2", "new_level1", ...))
Combine levels in a factor variable
main_factor_variable <- fct_collapse(main_factor_variable,
new_level1 = c("old_level1", "old_level2"),
new_level2 = c("old_level3", "old_level4"), ...)
That’s it.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language.