<- c("Dec", "Apr", "Jan", "Mar") x
Pre-lecture materials
Read ahead
Acknowledgements
Material for this lecture was borrowed and adopted from
- Wrangling Categorical Data in R by Amelia McNamara, Nicholas J Horton
- https://r4ds.had.co.nz/factors
Learning objectives
Introduction
Factors are used for working with categorical variables, or variables that have a fixed and known set of possible values (income bracket, U.S. state, political affiliation).
Factors are useful when:
- You want to include categorical variables in regression models
- You want to plot categorical data (e.g. want to map categorical variables to aesthetic attributes)
- You want to display character vectors in a non-alphabetical order
Factor basics
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:
<- c(
month_levels "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
)
Now we can create a factor with the factor()
function defining the levels
argument:
<- factor(x, levels = month_levels)
y y
[1] Dec Apr Jan Mar
Levels: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
We can see what happens if we try to sort the factor:
sort(y)
[1] Jan Mar Apr Dec
Levels: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
We can also check the attributes of the factor:
attributes(y)
$levels
[1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
$class
[1] "factor"
If you want to access the set of levels directly, you can do so with levels()
:
levels(y)
[1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
Challenges working with categorical data
Working with categorical data can really helpful in many situations, but it also be challenging.
For example,
- What if the original data source for where the categorical data is getting ingested changes?
- If a domain expert is providing spreadsheet data at regular intervals, code that worked on the initial data may not generate an error message, but could silently produce incorrect results.
- What if a new level of a categorical data is added in an updated dataset?
- When categorical data are coded with numerical values, it can be easy to break the relationship between category numbers and category labels without realizing it, thus losing the information encoded in a variable.
- Let’s consider an example of this below.
This result is unexpected because base::as.numeric()
is intended to recover numeric information by coercing a character variable.
This behavior of the factor()
function feels unexpected at best.
Another example of unexpected behavior is how the function will silently make a missing value because the values in the data and the levels do not match.
factor("a", levels="c")
[1] <NA>
Levels: c
The unfortunate behavior of factors in R has led to an online movement against the default behavior of many data import functions to make factors out of any variable composed as strings.
The tidyverse is part of this movement, with functions from the readr
package defaulting to leaving strings as-is. (Others have chosen to add options(stringAsFactors=FALSE)
into their start up commands.)
Factors when modeling data
So if factors are so troublesome, what’s the point of them in the first place?
Factors are still necessary for some data analytic tasks. The most salient case is in statistical modeling.
When you pass a factor variable into lm()
or glm()
, R automatically creates indicator (or more colloquially ‘dummy’) variables for each of the levels and picks one as a reference group.
For simple cases, this behavior can also be achieved with a character vector.
However, to choose which level to use as a reference level or to order classes, factors must be used.
Memory req for factors and character strings
Consider a large character string such as income_level
corresponding to a categorical variable.
<- c(rep("low",10000),
income_level rep("medium",10000),
rep("high",10000))
In early versions of R, storing categorical data as a factor variable was considerably more efficient than storing the same data as strings, because factor variables only store the factor labels once.
However, R now uses a global string pool, so each unique string is only stored once, which means storage is now less of an issue.
format(object.size(income_level), units="Kb") # size of the character string
[1] "234.6 Kb"
format(object.size(factor(income_level)), units="Kb") # size of the factor
[1] "117.8 Kb"
Summary
Factors can be really useful in many data analytic tasks, but the base R functions to work with factors can lead to some unexpected behavior that can catch new R users.
Let’s introduce a package to make wrangling factors easier.
forcats
Next, we will introduce the forcats
package, which is part of the core tidyverse
, but can also be loaded directly
library(forcats)
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.
Modifying factor order
It’s often useful to change the order of the factor levels in a visualization.
Let’s explore the relig
(religion) factor:
%>%
gss_cat count(relig)
# A tibble: 15 × 2
relig n
<fct> <int>
1 No answer 93
2 Don't know 15
3 Inter-nondenominational 109
4 Native american 23
5 Christian 689
6 Orthodox-christian 95
7 Moslem/islam 104
8 Other eastern 32
9 Hinduism 71
10 Buddhism 147
11 Other 224
12 None 3523
13 Jewish 388
14 Catholic 5124
15 Protestant 10846
We see there are 15 categories in the gss_cat
dataset.
attributes(gss_cat$relig)
$levels
[1] "No answer" "Don't know"
[3] "Inter-nondenominational" "Native american"
[5] "Christian" "Orthodox-christian"
[7] "Moslem/islam" "Other eastern"
[9] "Hinduism" "Buddhism"
[11] "Other" "None"
[13] "Jewish" "Catholic"
[15] "Protestant" "Not applicable"
$class
[1] "factor"
The first level is “No answer” followed by “Don’t know”, and so on.
Imagine you want to explore the average number of hours spent watching TV (tvhours
) per day across religions (relig
):
<- gss_cat %>%
relig_summary group_by(relig) %>%
summarise(tvhours = mean(tvhours, na.rm = TRUE),
n = n())
%>%
relig_summary ggplot(aes(x = tvhours, y = relig)) +
geom_point()
The y-axis lists the levels of the relig
factor in the order of the levels.
However, it is hard to read this plot because there’s no overall pattern.
fct_reorder
We can improve it by reordering the levels of relig
using fct_reorder()
. fct_reorder(.f, .x, .fun)
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 ofx
for each value off
. The default value ismedian
.
%>%
relig_summary ggplot(aes(x = tvhours,
y = fct_reorder(.f = relig, .x = tvhours))) +
geom_point()
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, I recommend moving them out of aes()
and into a separate mutate()
step.
fct_relevel
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.
%>%
rincome_summary ggplot(aes(age, fct_relevel(rincome, "Not applicable"))) +
geom_point()
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.
<-
by_age %>%
gss_cat filter(!is.na(age)) %>%
count(age, marital) %>%
group_by(age) %>%
mutate(prop = n / sum(n))
%>%
by_age ggplot(aes(age, prop, colour = marital)) +
geom_line(na.rm = TRUE)
%>%
by_age ggplot(aes(age, prop, colour = fct_reorder2(marital, age, prop))) +
geom_line() +
labs(colour = "marital")
fct_infreq
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.
%>%
gss_cat mutate(marital = marital %>% fct_infreq() %>% fct_rev()) %>%
ggplot(aes(marital)) +
geom_bar()
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.
fct_recode
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
:
%>%
gss_cat count(partyid)
# A tibble: 10 × 2
partyid n
<fct> <int>
1 No answer 154
2 Don't know 1
3 Other party 393
4 Strong republican 2314
5 Not str republican 3032
6 Ind,near rep 1791
7 Independent 4119
8 Ind,near dem 2499
9 Not str democrat 3690
10 Strong democrat 3490
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
- the old values go on the right
%>%
gss_cat 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")) %>%
count(partyid)
# A tibble: 10 × 2
partyid n
<fct> <int>
1 No answer 154
2 Don't know 1
3 Other party 393
4 Republican, strong 2314
5 Republican, weak 3032
6 Independent, near rep 1791
7 Independent 4119
8 Independent, near dem 2499
9 Democrat, weak 3690
10 Democrat, strong 3490
To combine groups, you can assign multiple old levels to the same new level:
%>%
gss_cat 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")) %>%
count(partyid)
# A tibble: 8 × 2
partyid n
<fct> <int>
1 Other 548
2 Republican, strong 2314
3 Republican, weak 3032
4 Independent, near rep 1791
5 Independent 4119
6 Independent, near dem 2499
7 Democrat, weak 3690
8 Democrat, strong 3490
Use this technique with care: if you group together categories that are truly different you will end up with misleading results.
fct_collapse
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:
%>%
gss_cat 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"))) %>%
count(partyid)
# A tibble: 4 × 2
partyid n
<fct> <int>
1 other 548
2 rep 5346
3 ind 8409
4 dem 7180
fct_lump_*
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.
%>%
gss_cat mutate(relig = fct_lump_lowfreq(relig)) %>%
count(relig)
# A tibble: 2 × 2
relig n
<fct> <int>
1 Protestant 10846
2 Other 10637
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:
%>%
gss_cat mutate(relig = fct_lump_n(relig, n = 10)) %>%
count(relig, sort = TRUE) %>%
print(n = Inf)
# A tibble: 10 × 2
relig n
<fct> <int>
1 Protestant 10846
2 Catholic 5124
3 None 3523
4 Christian 689
5 Other 458
6 Jewish 388
7 Buddhism 147
8 Inter-nondenominational 109
9 Moslem/islam 104
10 Orthodox-christian 95
Read the documentation to learn about fct_lump_min()
and fct_lump_prop()
which are useful in other cases.
Ordered factors
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:
ordered(c("a", "b", "c"))
[1] a b c
Levels: a < b < c
However, in practice, ordered()
factors behave very similarly to regular factors.
Post-lecture materials
Final Questions
Here are some post-lecture questions to help you think about the material discussed.