Factor Levels (R)
The levels of a factor are its set of distinct categories. They define which values are valid, their order, and how the factor appears in tables, plots, and statistical models.
R
Every factor carries a levels attribute listing its unique categories. By default factor() sorts levels alphabetically, but you can set them explicitly with the levels = argument to control order — important for ordered factors and for which category a model treats as the baseline (the first level).
Inspect levels with levels(f) and reorder or rename them by reassigning. The first level is the reference category in regression, so deliberately choosing it changes how coefficients are interpreted. Dropping unused levels with droplevels() cleans up after subsetting.
Level order also drives the order of bars in a ggplot2 chart or columns in table(). Managing levels carefully is what separates correct categorical analysis from misleading output.
Syntax
levels(f)
factor(x, levels = c("low", "med", "high"))Examples
R
grade <- factor(c("B", "A", "C"),
levels = c("A", "B", "C"),
ordered = TRUE)
print(grade < "B")
print(levels(grade))Output:
[1] FALSE TRUE FALSE
[1] "A" "B" "C"