Reorder Levels of Factor without Changing Order of Values in R (Example)
In this article you’ll learn how to reorder factor levels in the R programming language.
The tutorial looks as follows:
- Introduction of Example Data
- Example: Reorder Factor Levels without Losing the Order of Values
- Video & Further Resources
If you want to learn more about these topics, keep reading:
Introduction of Example Data
As a first step, we need to create a factor vector in R as basement for the following example:
x <- factor(c("a", "BBB", "A", "CC")) # Create example factor x # Print factor values and levels # [1] a BBB A CC # Levels: a A BBB CC
Our example factor consists of four values and four factor levels. The factor levels are sorted alphabetically, i.e. a A BBB CC.
Now, let’s change the order of these factor levels…
Example: Reorder Factor Levels without Losing the Order of Values
If we want to modify the ordering of the factor levels of our example vector, then we can use the following R syntax:
x_mod <- factor(x, c("BBB", "CC", "a", "A")) # Modify factor levels x_mod # Print modified values and levels # [1] a BBB A CC # Levels: BBB CC a A
As you can see, we specified the order of the levels manually within the factor function. The factor levels of the updated factor vector are BBB CC a A. However, the order of the values of our vector were preserved.
Video & Further Resources
Would you like to learn more about factor vectors in R? Then you may watch the following video instruction of my YouTube channel. I show the R codes of this tutorial in the video:
In addition, you may read some of the other articles on this website. You can find some interesting posts here:
- Drop Factor Levels of Vector & Data Frame
- Warning: invalid factor level, NA generated
- recode & recode_factor R Functions of dplyr Package
- The R Programming Language
Summary: This article illustrated how to reorder factor levels, but preserve the order of values in R programming. Don’t hesitate to let me know in the comments section, in case you have further questions.