STAT 545 - Fall 2026
From today’s class, students are anticipated to be able to:
Reorder levels within factors according to various principles
Think critically about the levels of a categorical variable
Throughout this lecture, we will be using functions from the following packages:
Factors represent categorical variables: variables that take on a fixed number of known values
Example, in the penguins data set, species is a factor with three levels: “Adelie”, “Chinstrap”, and “Gentoo”. We can see this by looking at the str() (structure) of the tibble:
Suppose in the penguins data set than instead of their names, species had levels:
“1” for Gentoo,
“2” for Adelie, and
3 for Chinstrap penguins
We see here that R assumes that species is a numeric variable, not a categorical variable. This means, R assumes “species” can take on any numeric value, such as 1.5, 2.567, or 5 (which doesn’t make sense for this variable!)
To ensure R knows that species is categorical, we can use:
Now we see that species is a factor with three levels!
To make our lives easier, we will work with factors through the forcats package loaded as part of the tidyverse.
By default, factors are ordered alphabetically or numerically.
However, in many cases factors have a logical ordering they should follow (i.e., elementary, secondary, post-secondary, graduate).
Reordering data can be useful for both data visualization and model fitting.
To see the current ordering of a factor variable, we can call levels().
We see here, the levels of the factor are ordered alphabetically.
There are many ways to reorder the levels of a factor in R. To reorder the levels of the factor, we can use built in R functions such as ordered():
Now, when we call str() on the penguins data, we see that the factor is explicitly ordered, with out new ordering:
forcatsLet’s look again at the original penguins data set and look at the frequency of each species using ggplot:
Notice that the ordering is alphabetical What would be a more effective ordering?
Notes:
forcatsLet’s order bars by largest to smallest (or smallest to largest) so readers can easily spot which species is the most common.
Two approaches:
edit the original tibble to have new factor ordering, or
order the factors directly in the ggplot2 call so that the original tibble isn’t overwritten.
forcatsOption A: Reorder Tibble Directly
To reorder the factor levels according to the frequency in the tibble:
We can then plot our data using penguins4:
forcatsOption B: Reorder the Factor in the ggplot Call
We can do these steps directly in ggplot without overwriting or making a new tibble!
We get the exact same plot with a single chunk of code! And, the original tibble penguins remains unchanged with the alphabetical ordering of the species factors.
Perhaps we may want to visualize that in our data set, there are no Emperor or King penguins. To do so, we can add “Emperor” and “King” as possible factor levels for species in our penguins data set. We do so by fct_expand()
Now we add to the visualization that there were no King or Emperor penguins collected in the data.
Let’s suppose we were only interested in comparing Adelie and Chinstrap penguins. We could drop the Gentoo level using forcats by:
Some categorical variables, like birthplace, can have a lot of unique levels.
There is no universally agreed upon rule as to what constitutes having “too many levels” in a categorical variable, as it often depends on the method(s) being used.
Some statisticians argue that you must have >10 observations per level (in our example, this means having 10 or more people in each birthplace)
So… how can you overcome this issue?
Use domain knowledge to combine similar levels
Group categories with low frequency together
Use a statistical method to combine similar levels
(Advanced) Use a regularization technique
(Advanced: for hierarchical data) Use the levels as a random effect
Variables related to race and ethnicity are often collected for studies involving human data.
Definition
Race: a group of people who are arbitrarily categorized according to common physical characteristics, regardless of language, culture or nationality, as per Statistics Canada.
Ethnicity: the shared cultural, linguistic or religious characteristics of a group of people having a common history, heritage or ancestry. While these terms are often used interchangeably, there is a distinct difference which we emphasize here.
There are a lot of unique races and ethnicities that one can collect information on
Oftentimes, these categories are coarsened to have a more reasonable number of possible levels
Doing so can omit complex racial and ethnic identities which are grouped into broader categories.
Coarsening the levels may also not acknowledge the unique lived experiences of smaller or mixed-race identities.
Such simplifications may lead marginalized groups to be underrepresented in studies, furthering the feeling of invisibility and a lack of belonging.
Discussion
In Canada, Métis have typically been recognized as a “mixed-descent identity” in studies source. How might this affect the Métis population?
Possible answer:
This undermines the Métis Nation as a self-governing Indigenous nation with associated rights and unique cultural experiences
For a summary on how Indigenous Peoples were represented in the Canadian Census from 1870 to 2021, see this paper.
When plotting or creating tables of demographic variables, an ordering needs to be decided on.
Discussion
White or Caucasian is frequently shown at the top of tables listing race and ethnicity, and is typically used as a reference group to which other groups are compared source.
Discuss in a small group how this may impact marginalized populations.
Possible answer:
There have been ongoing discussions on how to appropriately include considerations of race and ethnicity into studies, including a guide for researchers in British Columbia..
Use your best judgement, and consider these impacts when handling data on race and ethnicity.
Consider consulting with Indigenous data stewards, ensuring you are respecting the principals of OCAP® and Data Sovereignty.
Try your hand at using factors by working through the factors portion of Worksheet A5.
Finished attempting all of the questions? Then do the optional R4DS Factors reading, and maybe even do some of the exercises for extra practice.