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:

To remove them, use droplevels():

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: