15.11 Removing Unused Levels from a Factor

15.11.1 Problem

You want to remove unused levels from a factor.

15.11.2 Solution

Sometimes, after processing your data you will have a factor that contains levels that are no longer used. Here’s an example:

sizes <- factor(c("small", "large", "large", "small", "medium"))
sizes <- sizes[1:3]
sizes
#> [1] small large large
#> Levels: large medium small

To remove them, use droplevels():

droplevels(sizes)
#> [1] small large large
#> Levels: large small

15.11.3 Discussion

The droplevels() function preserves the order of factor levels. You can use the except parameter to keep particular levels.

The tidyverse way: Use fct_drop() from the forcats package:

fct_drop(sizes)
#> [1] small large large
#> Levels: large small