R Factor Levels
Factor levels can be renamed, reordered and dropped after a factor is built. The values in the factor follow their level through each change.
Rename levels in place
The levels start as high, low and mid in level order. The new names H, L and M replace them in that same order, so high becomes H and low becomes L.
sizes <- factor(c("low", "high", "low", "mid"))
print(sizes)
levels(sizes) <- c("H", "L", "M")
print(sizes)
print(levels(sizes))Move a level first
relevel() takes the factor and the level to move first. The values stay the same and the level order starts with b.
grade <- factor(c("b", "a", "b"))
print(grade)
grade <- relevel(grade, "b")
print(grade)
print(levels(grade))Subset keeps levels
The subset holds only low values. Its level list still shows all three levels until droplevels() runs.
sizes <- factor(c("high", "low", "mid", "low"))
small <- sizes[sizes == "low"]
print(small)
print(droplevels(small))A value outside the levels
This block stores the text c in a factor whose levels are a and b. The block prints nothing and its whole output is the warning.
f <- factor(c("a", "b"))
f[1] <- "c"The damaged factor
Storing NA directly builds the same missing entry the warning left behind. The print shows a missing first value with the levels a and b unchanged.
f <- factor(c("a", "b"))
f[1] <- NA
print(f)Example
sizes <- factor(c("low", "high", "mid", "low"))
levels(sizes) <- c("H", "L", "M")
sizes <- relevel(sizes, "L")
kept <- sizes[sizes == "L"]
print(kept)
print(droplevels(kept))Key points
- Assigning to levels() renames the levels in place, in level order.
- relevel() moves one named level to the front of the level order.
- Subsetting a factor keeps every level, even the levels no value uses.
- droplevels() removes the levels that no value uses.
- Storing a value that is not a level makes that entry missing.
In this example the levels are first renamed to H, L and M. relevel() then moves L to the front and the subset keeps only the L values, so droplevels() leaves L as the only level.
Note
The rename list follows the current level order, not the order the values appear in the data.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does droplevels() remove from a factor?