In R, factors are used to work with categorical variables, variables that have a fixed and known set of possible values. They are also useful when you want to display character vectors with non-alphabetical order.
Historically, factors were much easier to work with than characters so many functions in base R automatically convert characters to factors. That means factors often crop up in places where they're not actually helpful. Fortunately, you don't need to worry about that in the tidyverse, and can focus on where factors are genuinely useful.
To get more historical context on factors, I'd reccommed [_stringsAsFactors: An unauthorized biography_](http://simplystatistics.org/2015/07/24/stringsasfactors-an-unauthorized-biography/) by Roger Peng, and [_stringsAsFactors = \<sigh\>_](http://notstatschat.tumblr.com/post/124987394001/stringsasfactors-sigh) by Thomas Lumley.
To work with factors, we'll use the __forcats__ packages which provides tools for dealing **cat**egorical variables (and it's an anagram of factors!). It provides a wide range of helpers for working with factors. We'll also need dplyr for some data manipulation, and ggplot2 for visualisation.
Typically you'll convert a factor from a character vector, using `factor()`. Apart from the character input, the most important argument are the valid __levels__:
Sometimes you'd prefer that the order of the levels match the order of the first appearnace in the data. You can do that during creation by setting levels to `unique(x)`, or after the with `fct_inorder()`:
In rest of this chapter, we're going to focus on `forcats::gss_cat`. It's a sample data from the [General Social Survey](http://gss.norc.org), which is a long-running US survey run by the the independent research organization NORC at the University of Chicago. The survey has thousands of questions, so in `gss_cat` I've selected a handful that will illustrate some common challenges you'll hit when working with factors.
These levels represent valid values that we simply did not see in this dataset. Unfortunately dplyr doesn't yet have a `drop` option, but it will in the future.
There are two main operations that you'll do time and time again when working with factors: changing the order of the levels, and changing the values of the levels. Those operation are described in the sections below.
It's often useful to change the order of the factors levels in a visualisation. For example, imagine you want to explore the average number of hours spend watching tv per day across religions:
It's a little hard to take in 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 to if there are multiple values of
`x` for each value of `f`. The default value is `median`.
Reordering religion makes it much easier to see that "Don't know" seems to watch much more, and Hinduism & Other Eastern religions watch much less.
As you start making more complicated transformations, I'd recommend moving them about out `aes()` and into a separate `mutate()` step. For example, you could rewrite the plot above as:
```{r, eval = FALSE}
relig %>%
mutate(relig = fct_reorder(relig, tvhours)) %>%
ggplot(aes(tvhours, relig)) +
geom_point()
```
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()` to reorder 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.
Another type of reordering is useful when you are colouring the lines on a plot. `fct_reorder2()` reorders the factor to by the `y` values associated the largest `x` values. This makes the plot easier to read because the line colours up with the legend.
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()`.
More powerful than changing the orders of the levels is to change 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`:
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:
The default behaviour is to progressively lump together the smallest groups, ensuring that the aggregate is still the smallest group. In this case it's not very helpful: it is true that the majority of Americans in this survey are Protestant, but we've probably over collapsed.