15.10 Changing the Names of Factor Levels

15.10.1 Problem

You want to change the names of levels in a factor.

15.10.3 Discussion

If you want to use two vectors, one with the original levels and one with the new ones, use do.call() with fct_recode().

Or, more concisely, we can do all of that in one go:

For a more traditional (and clunky) base R method for renaming factor levels, use the levels()<- function:

If you are renaming all your factor levels, there is a simpler method. You can pass a list to levels()<-:

With this method, all factor levels must be specified in the list; if any are missing, they will be replaced with NA.

It’s also possible to rename factor levels by position, but this is somewhat inelegant:

It’s safer to rename factor levels by name rather than by position, since you will be less likely to make a mistake (and mistakes here may be hard to detect). Also, if your input data set changes to have more or fewer levels, the numeric positions of the existing levels could change, which could cause serious but nonobvious problems for your analysis.

15.10.4 See Also

If, instead of a factor, you have a character vector with items to rename, see Recipe 15.12.