How can I reorder factor levels in R?

Reordering factor levels in R refers to the process of changing the order of the levels within a factor variable. This can be useful for visualizing data or for conducting statistical analyses where the order of the levels is important. In order to reorder factor levels in R, the “factor” function can be used with the “levels” argument to specify a desired order, or the “reorder” function can be used to reorder levels in alphabetical order. This allows for flexibility in organizing and analyzing data in R.

Reorder Factor Levels in R (With Examples)


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 regionlevels(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 regionlevels(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 regionbarplot(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