How to order factors in R

Importing data into R is awesome and easy. The annoying part can be where you need to create a visualization only to find that the factors are in the order in which they were imported — randomly unless you’ve preordered the data.

Recently I was creating a heat map of website visits by weekday and hour to a website. The weekdays were in random orders and didn’t make sense when reading the diagram.

The order() function in base R solves this problem.

‘dat’ is the general name I set for imported data. In this case, a data frame. The weekday column contains the three letter abbreviation of the weekday and is a factor (categorical variable). So, we tell R to take the weekday column and set the order of the factor to the specified vector. Then, assign the new factor order back to the column in the data frame.

dat$weekday = ordered(dat$weekday, levels = c(“SUN”, “MON”, “TUE”, “WED”, “THU”, “FRI”, “SAT”))

Now, when the visualization is rendered, the weekdays are in the correct order.

Originally published at what do the data say?.