The goal of this tutorial is to reorder the levels of a factor. By default the levels of a factor are ordered alphabetically which can be convinient in some cases but we may want to define a different order.
# In this example we will use the open repository of plants classification Iris.
data("iris")
str(iris)
## 'data.frame': 150 obs. of 5 variables:
## $ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
## $ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
## $ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
## $ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
## $ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
# The levels always come in alphabetical order
# We may want to change that
levels(iris$Species)
## [1] "setosa" "versicolor" "virginica"
# We can change the order of the levels
# Let's put versicolor, virginica, setosa
iris$Species <- factor(iris$Species,levels(iris$Species)[c(2,3,1)])
levels(iris$Species)
## [1] "versicolor" "virginica" "setosa"
# Let's put back the original order
iris$Species <- factor(as.character(iris$Species))
levels(iris$Species)
## [1] "setosa" "versicolor" "virginica"
# Now we put the levels in reverse order
iris$Species <- factor(iris$Species,levels(iris$Species)[3:1])
levels(iris$Species)
## [1] "virginica" "versicolor" "setosa"
In this tutorial we have learnt how to change the order of the levels of a factor. This could be useful when working with days of the week and they appear by default in alphabetical order.