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 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 order(levels(df$region)),] #create barplot and place bars in order based on factor levels for region barplot(df$sales, names=df$region)
Notice how the bars are in the order of the factor levels that we specified for region.
You can find more R tutorials on this page.