How to Reorder Factor Levels in R (With Examples)

In R, you can reorder factor levels by using the factor() and levels() functions. The factor() function is used to convert a vector into a factor, while the levels() function is used to define the order of factor levels. This can be done by passing a vector of level names to the levels() function. Once the levels have been reordered, the factor can be used in data analysis. Examples of this process are provided in the article.


Occasionally you may want to re-order the levels of some factor variable in R. Fortunately this is easy to do using the following syntax:

factor_variable <- factor(factor_variable, levels=c('this', 'that', 'those', ...))

The following example show how to use this function in practice.

Example: Reorder Factor Levels in R

First, let’s create a data frame with one factor variable and one numeric variable:

#create data frame
df <- data.frame(region=factor(c('A', 'B', 'C', 'D', 'E')),
                 sales=c(12, 18, 21, 14, 34))

#view data frame
df

  region sales
1      A    12
2      B    18
3      C    21
4      D    14
5      E    34

We can use the levels() argument to get the current levels of the factor variable region:

#display factor levels for region
levels(df$region)

[1] "A" "B" "C" "D" "E"

And we can use the following syntax to re-order the factor levels:

#re-order factor levels for region
df$region <- factor(df$region, levels=c('A', 'E', 'D', 'C', 'B'))

#display factor levels for region
levels(df$region)

[1] "A" "E" "D" "C" "B"

The factor levels are now in the order that we specified using the levels argument.

If we then want to create a barplot in R and order the bars based on the factor levels of region, we can use the following syntax:

#re-order data frame based on factor levels for region
df <- df[order(levels(df$region)),]

#create barplot and place bars in order based on factor levels for region
barplot(df$sales, names=df$region)

Reorder factor levels for barplot in R

Notice how the bars are in the order of the factor levels that we specified for region.


You can find more R tutorials on .

x