To modify factor levels in R, you can use the levels()
function to set new levels. This is useful when you need to rename, reorder, or add new levels to a factor.
In this example,
colors
which contains the values 'red'
, 'green'
, 'blue'
, and 'red'
. This vector represents categorical data.factor()
function to convert the colors
vector into a factor. We assign the result to a variable named colors_factor
. The factor()
function automatically identifies the unique levels of the vector.levels()
function to access the levels of the colors_factor
. We assign new names to the levels by setting levels(colors_factor)
to a new vector of level names c('Red', 'Green', 'Blue')
.colors_factor
to the console to see the renamed factor levels. This allows us to verify the changes in the factor levels.colors <- c('red', 'green', 'blue', 'red')
colors_factor <- factor(colors)
levels(colors_factor) <- c('Red', 'Green', 'Blue')
print(colors_factor)
[1] Red Green Blue Red Levels: Red Green Blue
In this example,
animals
which contains the values 'cat'
, 'dog'
, 'bird'
, and 'cat'
. This vector represents categorical data.factor()
function to convert the animals
vector into a factor. We assign the result to a variable named animals_factor
. The factor()
function automatically identifies the unique levels of the vector.factor()
function again to reorder the levels of the animals_factor
by specifying the levels in the desired order: c('dog', 'cat', 'bird')
.animals_factor
to the console to see the reordered factor levels. This allows us to verify the new order of the factor levels.animals <- c('cat', 'dog', 'bird', 'cat')
animals_factor <- factor(animals)
animals_factor <- factor(animals_factor, levels = c('dog', 'cat', 'bird'))
print(animals_factor)
[1] cat dog bird cat Levels: dog cat bird
In this example,
sizes
which contains the values 'small'
, 'medium'
, and 'large'
. This vector represents categorical data.factor()
function to convert the sizes
vector into a factor. We assign the result to a variable named sizes_factor
. The factor()
function automatically identifies the unique levels of the vector.levels()
function to add new levels to the sizes_factor
by setting levels(sizes_factor)
to a new vector of level names c('small', 'medium', 'large', 'extra large')
.sizes_factor
to the console to see the added factor levels. This allows us to verify the new levels in the factor.sizes <- c('small', 'medium', 'large')
sizes_factor <- factor(sizes)
levels(sizes_factor) <- c('small', 'medium', 'large', 'extra large')
print(sizes_factor)
[1] small medium large Levels: small medium large extra large
In this tutorial, we learned How to Modify Factor Levels in R language with well detailed examples.