2016-08-17 06:06:51 +08:00
# Factors
## Introduction
2022-05-04 05:02:13 +08:00
Factors are used for categorical variables, variables that have a fixed and known set of possible values.
2021-02-21 23:40:40 +08:00
They are also useful when you want to display character vectors in a non-alphabetical order.
2016-08-17 06:06:51 +08:00
2022-05-04 05:02:13 +08:00
If, after reading this chapter, you want to learn more about factors, I recommend reading Amelia McNamara and Nicholas Horton's paper, [*Wrangling categorical data in R*](https://peerj.com/preprints/3163/).
This paper lays out some of the history discussed in [*stringsAsFactors: An unauthorized biography*](https://simplystatistics.org/posts/2015-07-24-stringsasfactors-an-unauthorized-biography/) and [*stringsAsFactors = \<sigh\>*](http://notstatschat.tumblr.com/post/124987394001/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!
2016-08-18 02:49:27 +08:00
2016-08-17 06:06:51 +08:00
### Prerequisites
2021-02-21 23:40:40 +08:00
To work with factors, we'll use the **forcats** package, which is part of the core tidyverse.
It provides tools for dealing with **cat**egorical variables (and it's an anagram of factors!) using a wide range of helpers for working with factors.
2016-08-17 06:06:51 +08:00
```{r setup, message = FALSE}
2016-10-04 01:30:24 +08:00
library(tidyverse)
2016-08-17 06:06:51 +08:00
```
## Creating factors
2016-10-04 22:00:33 +08:00
Imagine that you have a variable that records month:
2016-08-17 06:06:51 +08:00
```{r}
2016-10-04 22:00:33 +08:00
x1 <- c("Dec", "Apr", "Jan", "Mar")
2016-08-17 23:23:57 +08:00
```
2016-10-04 22:00:33 +08:00
Using a string to record this variable has two problems:
2021-02-21 23:40:40 +08:00
1. There are only twelve possible months, and there's nothing saving you from typos:
2016-10-04 22:00:33 +08:00
```{r}
x2 <- c("Dec", "Apr", "Jam", "Mar")
```
2021-02-21 23:40:40 +08:00
2. It doesn't sort in a useful way:
2016-10-04 22:00:33 +08:00
```{r}
sort(x1)
```
2021-02-21 23:40:40 +08:00
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**:
2016-10-04 22:00:33 +08:00
```{r}
month_levels <- c(
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
)
```
Now you can create a factor:
```{r}
y1 <- factor(x1, levels = month_levels)
y1
sort(y1)
```
And any values not in the set will be silently converted to NA:
```{r}
y2 <- factor(x2, levels = month_levels)
y2
```
2016-10-17 02:56:27 +08:00
If you want a warning, you can use `readr::parse_factor()`:
2016-08-17 06:06:51 +08:00
2016-08-17 23:23:57 +08:00
```{r}
2016-10-04 22:00:33 +08:00
y2 <- parse_factor(x2, levels = month_levels)
2016-08-17 06:06:51 +08:00
```
2016-08-17 23:23:57 +08:00
If you omit the levels, they'll be taken from the data in alphabetical order:
2016-08-17 06:06:51 +08:00
```{r}
2016-10-04 22:00:33 +08:00
factor(x1)
2016-08-17 23:23:57 +08:00
```
2021-02-21 23:40:40 +08:00
Sometimes you'd prefer that the order of the levels match the order of the first appearance in the data.
You can do that when creating the factor by setting levels to `unique(x)`, or after the fact, with `fct_inorder()`:
2016-08-17 23:23:57 +08:00
```{r}
2016-10-04 22:00:33 +08:00
f1 <- factor(x1, levels = unique(x1))
2016-08-18 02:49:27 +08:00
f1
2016-08-17 23:23:57 +08:00
2022-02-24 03:15:52 +08:00
f2 <- x1 |> factor() |> fct_inorder()
2016-08-18 02:49:27 +08:00
f2
2016-08-17 23:23:57 +08:00
```
2016-08-18 05:35:33 +08:00
If you ever need to access the set of valid levels directly, you can do so with `levels()`:
2016-08-17 23:23:57 +08:00
```{r}
2016-08-18 02:49:27 +08:00
levels(f2)
2016-08-17 23:23:57 +08:00
```
## General Social Survey
2016-08-17 06:06:51 +08:00
2022-05-04 05:02:13 +08:00
For the rest of this chapter, we're going to use `forcats::gss_cat`.
It's a sample of data from the [General Social Survey](http://gss.norc.org), a long-running US survey conducted by the independent research organization NORC at the University of Chicago.
2021-02-21 23:40:40 +08:00
The survey has thousands of questions, so in `gss_cat` I've selected a handful that will illustrate some common challenges you'll encounter when working with factors.
2016-08-17 06:06:51 +08:00
```{r}
2016-08-17 23:23:57 +08:00
gss_cat
2016-08-17 06:06:51 +08:00
```
2016-08-18 02:49:27 +08:00
(Remember, since this dataset is provided by a package, you can get more information about the variables with `?gss_cat`.)
2021-02-21 23:40:40 +08:00
When factors are stored in a tibble, you can't see their levels so easily.
One way to see them is with `count()`:
2016-08-17 06:06:51 +08:00
```{r}
2022-02-24 03:15:52 +08:00
gss_cat |>
2016-08-17 06:06:51 +08:00
count(race)
```
2016-08-18 02:49:27 +08:00
Or with a bar chart:
2016-08-17 06:06:51 +08:00
```{r}
2022-05-04 05:02:13 +08:00
#| fig.alt: >
#| A bar chart showing the distribution of race. There are ~2000
#| records with race "Other", 3000 with race "Black", and other
#| 15,000 with race "White".
2016-08-18 05:35:33 +08:00
ggplot(gss_cat, aes(race)) +
2016-08-17 06:06:51 +08:00
geom_bar()
```
2021-02-21 23:40:40 +08:00
By default, ggplot2 will drop levels that don't have any values.
You can force them to display with:
2016-08-17 06:06:51 +08:00
```{r}
2022-05-04 05:02:13 +08:00
#> fig.alt: >
#> The same bar chart as the last plot, but now with an missing bar on
#> the far right with label "Not applicable".
2016-08-18 05:35:33 +08:00
ggplot(gss_cat, aes(race)) +
geom_bar() +
2016-08-17 06:06:51 +08:00
scale_x_discrete(drop = FALSE)
```
2021-02-21 23:40:40 +08:00
These levels represent valid values that simply did not occur in this dataset.
In dplyr::count() set the `.drop` option to `FALSE`, to show these.
2021-02-09 00:30:40 +08:00
```{r}
2022-02-24 03:15:52 +08:00
gss_cat |>
2022-05-04 05:02:13 +08:00
count(race, .drop = FALSE)
2021-02-09 00:30:40 +08:00
```
2016-08-18 02:49:27 +08:00
2021-02-21 23:40:40 +08:00
When working with factors, the two most common operations are changing the order of the levels, and changing the values of the levels.
Those operations are described in the sections below.
2016-08-17 23:23:57 +08:00
### Exercise
2021-02-21 23:40:40 +08:00
1. Explore the distribution of `rincome` (reported income).
What makes the default bar chart hard to understand?
How could you improve the plot?
2016-08-18 05:35:33 +08:00
2021-02-21 23:40:40 +08:00
2. What is the most common `relig` in this survey?
What's the most common `partyid`?
2016-08-18 05:35:33 +08:00
2021-02-21 23:40:40 +08:00
3. Which `relig` does `denom` (denomination) apply to?
How can you find out with a table?
2022-05-04 05:02:13 +08:00
How can you find out with a visualization?
2016-08-17 06:06:51 +08:00
## Modifying factor order
2022-05-04 05:02:13 +08:00
It's often useful to change the order of the factor levels in a visualization.
2021-02-21 23:40:40 +08:00
For example, imagine you want to explore the average number of hours spent watching TV per day across religions:
2016-08-17 23:23:57 +08:00
2016-08-17 06:06:51 +08:00
```{r}
2022-05-04 05:02:13 +08:00
#| fig.alt: >
#| A scatterplot of with tvhours on the x-axis and religion on the y-axis.
#| The y-axis is ordered seemingly aribtrarily making it hard to get
#| any sense of overall pattern.
2022-02-24 03:15:52 +08:00
relig_summary <- gss_cat |>
group_by(relig) |>
2016-08-17 06:06:51 +08:00
summarise(
age = mean(age, na.rm = TRUE),
tvhours = mean(tvhours, na.rm = TRUE),
n = n()
)
2022-05-04 05:02:13 +08:00
ggplot(relig_summary, aes(tvhours, relig)) +
geom_point()
2016-08-17 06:06:51 +08:00
```
2021-02-21 23:40:40 +08:00
It is difficult to interpret 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:
2016-08-18 02:49:27 +08:00
2021-02-21 23:40:40 +08:00
- `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 is `median`.
2016-08-17 23:23:57 +08:00
```{r}
2022-05-04 05:02:13 +08:00
#| fig.alt: >
#| The same scatterplot as above, but now the religion is displayed in
#| increasing order of tvhours. "Other eastern" has the fewest tvhours
#| under 2, and "Don't know" has the highest (over 5).
2017-05-04 20:07:34 +08:00
ggplot(relig_summary, aes(tvhours, fct_reorder(relig, tvhours))) +
2016-08-17 23:23:57 +08:00
geom_point()
```
2016-08-18 05:35:33 +08:00
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.
2016-08-18 02:49:27 +08:00
2021-02-21 23:40:40 +08:00
As you start making more complicated transformations, I'd recommend moving them out of `aes()` and into a separate `mutate()` step.
For example, you could rewrite the plot above as:
2016-08-18 02:49:27 +08:00
```{r, eval = FALSE}
2022-02-24 03:15:52 +08:00
relig_summary |>
mutate(relig = fct_reorder(relig, tvhours)) |>
2016-08-18 05:35:33 +08:00
ggplot(aes(tvhours, relig)) +
2022-05-04 05:02:13 +08:00
geom_point()
2016-08-18 02:49:27 +08:00
```
2021-02-21 23:40:40 +08:00
2016-08-18 02:49:27 +08:00
What if we create a similar plot looking at how average age varies across reported income level?
2016-08-17 06:06:51 +08:00
```{r}
2022-05-04 05:02:13 +08:00
#| fig.alt: >
#| A scatterplot with age on the x-axis and income on the y-axis. Income
#| has been reordered in order of average age which doesn't make much
#| sense. One section of the y-axis goes from $6000-6999, then <$1000,
#| then $8000-9999.
2022-02-24 03:15:52 +08:00
rincome_summary <- gss_cat |>
group_by(rincome) |>
2016-08-17 06:06:51 +08:00
summarise(
age = mean(age, na.rm = TRUE),
tvhours = mean(tvhours, na.rm = TRUE),
n = n()
)
2022-05-04 05:02:13 +08:00
ggplot(rincome_summary, aes(age, fct_reorder(rincome, age))) +
geom_point()
2016-08-17 23:23:57 +08:00
```
2016-08-17 06:06:51 +08:00
2021-02-21 23:40:40 +08:00
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.
2016-08-18 02:49:27 +08:00
2021-02-21 23:40:40 +08:00
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.
2016-08-17 06:06:51 +08:00
```{r}
2022-05-04 05:02:13 +08:00
#| fig.alt: >
#| The same scatterplot but now "Not Applicable" is displayed at the
#| bottom of the y-axis. Generally there is a positive association
#| between income and age, and the income band with the highest average
#| age is "Not applicable".
2017-05-04 20:07:34 +08:00
ggplot(rincome_summary, aes(age, fct_relevel(rincome, "Not applicable"))) +
2016-08-17 23:23:57 +08:00
geom_point()
```
2016-08-18 02:49:27 +08:00
Why do you think the average age for "Not applicable" is so high?
2016-08-17 23:23:57 +08:00
2022-05-04 05:02:13 +08:00
Another type of reordering is useful when you are coloring the lines on a plot.
2021-02-21 23:40:40 +08:00
`fct_reorder2()` reorders the factor by the `y` values associated with the largest `x` values.
2022-05-04 05:02:13 +08:00
This makes the plot easier to read because the line colurs line up with the legend.
2016-08-18 02:49:27 +08:00
```{r, fig.align = "default", out.width = "50%", fig.width = 4}
2022-05-04 05:02:13 +08:00
#| fig.alt:
#| - >
#| A line plot with age on the x-axis and proportion on the y-axis.
#| There is one line for each category of marital status: no answer,
#| never married, separated, divorced, widowed, and married. It is
#| a little hard to read the plot because the order of the legend is
#| unrelated to the lines on the plot.
#| - >
#| Rearranging the legend makes the plot easier to read because the
#| legend colours now match the order of the lines on the far right
#| of the plot. You can see some unsuprising patterns: the proportion
#| never marred decreases with age, married forms an upside down U
#| shape, and widowed starts off low but increases steeply after age
#| 60.
2022-02-24 03:15:52 +08:00
by_age <- gss_cat |>
filter(!is.na(age)) |>
count(age, marital) |>
group_by(age) |>
2022-05-04 05:02:13 +08:00
mutate(
prop = n / sum(n)
)
2016-08-17 06:06:51 +08:00
2016-08-18 05:35:33 +08:00
ggplot(by_age, aes(age, prop, colour = marital)) +
2016-08-18 02:49:27 +08:00
geom_line(na.rm = TRUE)
2016-08-17 06:06:51 +08:00
2016-08-18 05:35:33 +08:00
ggplot(by_age, aes(age, prop, colour = fct_reorder2(marital, age, prop))) +
2016-08-17 23:23:57 +08:00
geom_line() +
labs(colour = "marital")
```
2016-08-17 06:06:51 +08:00
2021-02-21 23:40:40 +08:00
Finally, for bar plots, you can use `fct_infreq()` to order levels in increasing frequency: this is the simplest type of reordering because it doesn't need any extra variables.
You may want to combine with `fct_rev()`.
2016-08-17 23:23:57 +08:00
```{r}
2022-05-04 05:02:13 +08:00
#| fig.alt: >
#| A bar char of marital status ordered in from least to most common:
#| no answer (~0), separated (~1,000), widowed (~2,000), divorced
#| (~3,000), never married (~5,000), married (~10,000).
2022-02-24 03:15:52 +08:00
gss_cat |>
mutate(marital = marital |> fct_infreq() |> fct_rev()) |>
2016-08-17 23:23:57 +08:00
ggplot(aes(marital)) +
2022-05-04 05:02:13 +08:00
geom_bar()
2016-08-17 06:06:51 +08:00
```
2016-08-17 23:23:57 +08:00
### Exercises
2021-02-21 23:40:40 +08:00
1. There are some suspiciously high numbers in `tvhours`.
Is the mean a good summary?
2016-08-17 23:23:57 +08:00
2021-02-21 23:40:40 +08:00
2. For each factor in `gss_cat` identify whether the order of the levels is arbitrary or principled.
2016-08-18 05:35:33 +08:00
2021-02-21 23:40:40 +08:00
3. Why did moving "Not applicable" to the front of the levels move it to the bottom of the plot?
2016-08-17 23:23:57 +08:00
2016-08-17 06:06:51 +08:00
## Modifying factor levels
2021-02-21 23:40:40 +08:00
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 `gss_cat$partyid`:
2016-08-17 23:23:57 +08:00
```{r}
2022-02-24 03:15:52 +08:00
gss_cat |> count(partyid)
2016-08-17 23:23:57 +08:00
```
2016-08-17 06:06:51 +08:00
2021-02-21 23:40:40 +08:00
The levels are terse and inconsistent.
Let's tweak them to be longer and use a parallel construction.
2016-08-17 06:06:51 +08:00
```{r}
2022-02-24 03:15:52 +08:00
gss_cat |>
2022-05-04 05:02:13 +08:00
mutate(
partyid = fct_recode(partyid,
"Republican, strong" = "Strong republican",
"Republican, weak" = "Not str republican",
"Independent, near rep" = "Ind,near rep",
"Independent, near dem" = "Ind,near dem",
"Democrat, weak" = "Not str democrat",
"Democrat, strong" = "Strong democrat"
)
) |>
2016-08-17 23:23:57 +08:00
count(partyid)
2016-08-17 06:06:51 +08:00
```
2016-08-18 05:35:33 +08:00
`fct_recode()` will leave levels that aren't explicitly mentioned as is, and will warn you if you accidentally refer to a level that doesn't exist.
2016-08-18 02:49:27 +08:00
To combine groups, you can assign multiple old levels to the same new level:
2016-08-17 23:23:57 +08:00
```{r}
2022-02-24 03:15:52 +08:00
gss_cat |>
2022-05-04 05:02:13 +08:00
mutate(
partyid = fct_recode(partyid,
"Republican, strong" = "Strong republican",
"Republican, weak" = "Not str republican",
"Independent, near rep" = "Ind,near rep",
"Independent, near dem" = "Ind,near dem",
"Democrat, weak" = "Not str democrat",
"Democrat, strong" = "Strong democrat",
"Other" = "No answer",
"Other" = "Don't know",
"Other" = "Other party"
)
) |>
2016-08-17 23:23:57 +08:00
count(partyid)
2016-08-18 05:35:33 +08:00
```
2016-08-17 23:23:57 +08:00
2016-08-18 02:49:27 +08:00
You must use this technique with care: if you group together categories that are truly different you will end up with misleading results.
2016-08-17 23:23:57 +08:00
2021-02-21 23:40:40 +08:00
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:
2016-08-17 06:06:51 +08:00
```{r}
2022-02-24 03:15:52 +08:00
gss_cat |>
2022-05-04 05:02:13 +08:00
mutate(
partyid = fct_collapse(partyid,
other = c("No answer", "Don't know", "Other party"),
rep = c("Strong republican", "Not str republican"),
ind = c("Ind,near rep", "Independent", "Ind,near dem"),
dem = c("Not str democrat", "Strong democrat")
)
) |>
2016-08-17 23:23:57 +08:00
count(partyid)
2016-08-17 06:06:51 +08:00
```
2021-02-21 23:40:40 +08:00
Sometimes you just want to lump together all the small groups to make a plot or table simpler.
2021-04-18 22:21:59 +08:00
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.
2016-08-17 23:23:57 +08:00
2016-08-17 06:06:51 +08:00
```{r}
2022-02-24 03:15:52 +08:00
gss_cat |>
mutate(relig = fct_lump_lowfreq(relig)) |>
2016-08-17 23:23:57 +08:00
count(relig)
```
2021-04-18 22:21:59 +08:00
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:
2016-08-17 23:23:57 +08:00
```{r}
2022-02-24 03:15:52 +08:00
gss_cat |>
mutate(relig = fct_lump_n(relig, n = 10)) |>
count(relig, sort = TRUE) |>
2016-08-18 02:49:27 +08:00
print(n = Inf)
2016-08-17 06:06:51 +08:00
```
2016-08-17 23:23:57 +08:00
### Exercises
2016-08-18 02:49:27 +08:00
2021-02-21 23:40:40 +08:00
1. How have the proportions of people identifying as Democrat, Republican, and Independent changed over time?
2016-08-18 02:49:27 +08:00
2021-04-18 22:21:59 +08:00
2. How could you collapse `rincome` into a small set of categories?
2021-02-21 23:40:40 +08:00
2021-04-18 22:21:59 +08:00
3. 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 argument `other_level` is "Other".)