0
0
R Programmingprogramming~5 mins

Releveling factors in R Programming

Choose your learning style9 modes available
Introduction

Releveling factors changes which category is treated as the main or reference group. This helps when comparing groups in data analysis.

When you want to change the baseline group in a survey result to compare others against it.
When plotting data and you want a specific category to appear first in the legend or axis.
When running a statistical model and you want to set a different reference group for clearer interpretation.
Syntax
R Programming
factor_variable <- relevel(factor_variable, ref = "new_reference_level")

The ref argument sets the new reference level.

The original factor variable is replaced or assigned to a new variable with the updated reference.

Examples
This sets "blue" as the reference level in the colors factor.
R Programming
colors <- factor(c("red", "blue", "green", "blue"))
colors <- relevel(colors, ref = "blue")
Here, "high" becomes the baseline category for the status factor.
R Programming
status <- factor(c("low", "medium", "high", "medium"))
status <- relevel(status, ref = "high")
Sample Program

This program shows the original order of factor levels, then changes the reference level to "banana" and prints the new order.

R Programming
fruit <- factor(c("apple", "banana", "cherry", "banana"))
print(levels(fruit))
fruit <- relevel(fruit, ref = "banana")
print(levels(fruit))
OutputSuccess
Important Notes

Releveling does not change the data values, only the order of levels.

Always check levels after releveling to confirm the reference changed.

Summary

Releveling sets a new baseline category in a factor.

This helps in comparisons and plotting by controlling which group is the reference.

Use relevel() with the ref argument to specify the new reference.