Chapter 12. Factors with forcats
Introduction
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 in a non-alphabetical order.
Historically, factors were much easier to work with than characters. As a result, many of the functions in base R automatically convert characters to factors. This means that 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 situations where factors are genuinely useful.
For more historical context on factors, I recommend stringsAsFactors: An unauthorized biography by Roger Peng, and stringsAsFactors = <sigh> by Thomas Lumley.
Prerequisites
To work with factors, we’ll use the forcats package, which provides tools for dealing with categorical variables (and it’s an anagram of factors!). It provides a wide range of helpers for working with factors. forcats is not part of the core tidyverse, so we need to load it explicitly.
library(tidyverse)library(forcats)
Creating Factors
Imagine that you have a variable that records month:
x1<-c("Dec","Apr","Jan","Mar")
Using a string to record this variable has two problems:
-
There are only twelve possible months, and there’s nothing saving you from typos:
x2<-c("Dec","Apr","Jam","Mar") -
It doesn’t sort in a useful way:
sort(x1)#> [1] "Apr" "Dec" "Jan" "Mar"
You can ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access