R uses factors to handle categorical variables, variables that have a fixed and known set of possible values. Historically, factors were much easier to work with than character vectors, so many base R functions automatically convert character vectors to factors. (For historical context, I recommend stringsAsFactors: An unauthorized biography by Roger Peng, and stringsAsFactors = <sigh> by Thomas Lumley. If you want to learn more about other approaches to working with factors and categorical data, I recommend Wrangling categorical data in R, by Amelia McNamara and Nicholas Horton.) These days, making factors automatically is no longer so helpful, so packages in the tidyverse never create them automatically.

However, factors are still useful when you have true categorical data, and when you want to override the ordering of character vectors to improve display. The goal of the forcats package is to provide a suite of useful tools that solve common problems with factors. If you’re not familiar with strings, the best place to start is the chapter on factors in R for Data Science.

Getting started

forcats is part of the core tidyverse, so you can load it with library(tidyverse) or library(forcats).


Factors are used to describe categorical variables with a fixed and known set of levels. You can create factors with the base factor() or readr::parse_factor():

The advantage of parse_factor() is that it will generate a warning if values of x are not valid levels:

Once you have the factor, forcats provides helpers for solving common problems.