16 Factors
16.1 Introduction
Factors are used for categorical variables, variables that have a fixed and known set of possible values. They are also useful when you want to display character vectors in a non-alphabetical order.
We’ll start by motivating why factors are needed for data analysis1 and how you can create them with factor()
. We’ll then introduce you to the gss_cat
dataset which contains a bunch of categorical variables to experiment with. You’ll then use that dataset to practice modifying the order and values of factors, before we finish up with a discussion of ordered factors.
16.1.1 Prerequisites
Base R provides some basic tools for creating and manipulating factors. We’ll supplement these with the forcats package, which is part of the core tidyverse. It provides tools for dealing with categorical variables (and it’s an anagram of factors!) using a wide range of helpers for working with factors.
16.2 Factor basics
Imagine that you have a variable that records month:
Using a string to record this variable has two problems:
There are only twelve possible months, and there’s nothing saving you from typos:
It doesn’t sort in a useful way:
You can fix both of these problems with a factor. To create a factor you must start by creating a list of the valid levels:
Now you can create a factor:
And any values not in the level will be silently converted to NA:
This seems risky, so you might want to use forcats::fct()
instead:
If you omit the levels, they’ll be taken from the data in alphabetical order:
Sorting alphabetically is slightly risky because not every computer will sort strings in the same way. So forcats::fct()
orders by first appearance:
If you ever need to access the set of valid levels directly, you can do so with levels()
:
You can also create a factor when reading your data with readr with col_factor()
:
16.4 Modifying factor order
It’s often useful to change the order of the factor levels in a visualization. For example, imagine you want to explore the average number of hours spent watching TV per day across religions:
It is hard to read this plot because there’s no overall pattern. We can improve it by reordering the levels of relig
using fct_reorder()
. fct_reorder()
takes three arguments:
.f
, the factor whose levels you want to modify..x
, a numeric vector that you want to use to reorder the levels.- Optionally,
.fun
, a function that’s used if there are multiple values of.x
for each value of.f
. The default value ismedian
.
Reordering religion makes it much easier to see that people in the “Don’t know” category watch much more TV, and Hinduism & Other Eastern religions watch much less.
As you start making more complicated transformations, we recommend moving them out of aes()
and into a separate mutate()
step. For example, you could rewrite the plot above as:
What if we create a similar plot looking at how average age varies across reported income level?
Here, arbitrarily reordering the levels isn’t a good idea! That’s because rincome
already has a principled order that we shouldn’t mess with. Reserve fct_reorder()
for factors whose levels are arbitrarily ordered.
However, it does make sense to pull “Not applicable” to the front with the other special levels. You can use fct_relevel()
. It takes a factor, .f
, and then any number of levels that you want to move to the front of the line.
Why do you think the average age for “Not applicable” is so high?
Another type of reordering is useful when you are coloring the lines on a plot. fct_reorder2(.f, .x, .y)
reorders the factor .f
by the .y
values associated with the largest .x
values. This makes the plot easier to read because the colors of the line at the far right of the plot will line up with the legend.
Finally, for bar plots, you can use fct_infreq()
to order levels in decreasing frequency: this is the simplest type of reordering because it doesn’t need any extra variables. Combine it with fct_rev()
if you want them in increasing frequency so that in the bar plot largest values are on the right, not the left.
16.4.1 Exercises
There are some suspiciously high numbers in
tvhours
. Is the mean a good summary?For each factor in
gss_cat
identify whether the order of the levels is arbitrary or principled.Why did moving “Not applicable” to the front of the levels move it to the bottom of the plot?
16.5 Modifying factor levels
More powerful than changing the orders of the levels is changing their values. This allows you to clarify labels for publication, and collapse levels for high-level displays. The most general and powerful tool is fct_recode()
. It allows you to recode, or change, the value of each level. For example, take the partyid
variable from the gss_cat
data frame:
The levels are terse and inconsistent. Let’s tweak them to be longer and use a parallel construction. Like most rename and recoding functions in the tidyverse, the new values go on the left and the old values go on the right:
fct_recode()
will leave the levels that aren’t explicitly mentioned as is, and will warn you if you accidentally refer to a level that doesn’t exist.
To combine groups, you can assign multiple old levels to the same new level:
Use this technique with care: if you group together categories that are truly different you will end up with misleading results.
If you want to collapse a lot of levels, fct_collapse()
is a useful variant of fct_recode()
. For each new variable, you can provide a vector of old levels:
Sometimes you just want to lump together the small groups to make a plot or table simpler. That’s the job of the fct_lump_*()
family of functions. fct_lump_lowfreq()
is a simple starting point that progressively lumps the smallest groups categories into “Other”, always keeping “Other” as the smallest category.
In this case it’s not very helpful: it is true that the majority of Americans in this survey are Protestant, but we’d probably like to see some more details! Instead, we can use the fct_lump_n()
to specify that we want exactly 10 groups:
Read the documentation to learn about fct_lump_min()
and fct_lump_prop()
which are useful in other cases.
16.5.1 Exercises
How have the proportions of people identifying as Democrat, Republican, and Independent changed over time?
How could you collapse
rincome
into a small set of categories?Notice there are 9 groups (excluding other) in the
fct_lump
example above. Why not 10? (Hint: type?fct_lump
, and find the default for the argumentother_level
is “Other”.)
16.6 Ordered factors
Before we go on, there’s a special type of factor that needs to be mentioned briefly: ordered factors. Ordered factors, created with ordered()
, imply a strict ordering and equal distance between levels: the first level is “less than” the second level by the same amount that the second level is “less than” the third level, and so on. You can recognize them when printing because they use <
between the factor levels:
In practice, ordered()
factors behave very similarly to regular factors. There are only two places where you might notice different behavior:
- If you map an ordered factor to color or fill in ggplot2, it will default to
scale_color_viridis()
/scale_fill_viridis()
, a color scale that implies a ranking. - If you use an ordered function in a linear model, it will use “polygonal contrasts”. These are mildly useful, but you are unlikely to have heard of them unless you have a PhD in Statistics, and even then you probably don’t routinely interpret them. If you want to learn more, we recommend
vignette("contrasts", package = "faux")
by Lisa DeBruine.
Given the arguable utility of these differences, we don’t generally recommend using ordered factors.
16.7 Summary
This chapter introduced you to the handy forcats package for working with factors, introducing you to the most commonly used functions. forcats contains a wide range of other helpers that we didn’t have space to discuss here, so whenever you’re facing a factor analysis challenge that you haven’t encountered before, I highly recommend skimming the reference index to see if there’s a canned function that can help solve your problem.
If you want to learn more about factors after reading this chapter, we recommend reading Amelia McNamara and Nicholas Horton’s paper, Wrangling categorical data in R. This paper lays out some of the history discussed in stringsAsFactors: An unauthorized biography and stringsAsFactors = <sigh>, and compares the tidy approaches to categorical data outlined in this book with base R methods. An early version of the paper helped motivate and scope the forcats package; thanks Amelia & Nick!
In the next chapter we’ll switch gears to start learning about dates and times in R. Dates and times seem deceptively simple, but as you’ll soon see, the more you learn about them, the more complex they seem to get!
They’re also really important for modelling.↩︎