forcats
A factor stores a fixed set of levels, and the order of those levels decides the order of
bars, boxes, facets, and legend keys in ggplot2. It also decides the reference level of a
model, so the first level of condition is the baseline that DESeq2 and lm() compare
against. Every forcats function starts with fct_ and returns a factor.
Quick reference
Section titled “Quick reference”| Function | Purpose |
|---|---|
fct() |
Create a factor, levels in order of appearance, error on unknown values |
fct_relevel() |
Set the order by hand, or with a function of the levels |
fct_reorder() |
Order by another variable, median by default |
fct_infreq() |
Order by frequency |
fct_inorder() |
Order by first appearance |
fct_rev() |
Reverse the order |
fct_recode() |
Rename levels with new = old |
fct_collapse() |
Merge levels into groups |
fct_other() |
Keep the named levels and pool the rest |
fct_lump_n(), fct_lump_min() |
Pool rare levels into Other |
fct_drop() |
Remove empty levels |
fct_na_value_to_level() |
Turn NA into a level |
The cell type labels are simulated for 300 PBMCs, named after the clusters of the pbmc3k
tutorial. factor() sorts the levels alphabetically.
library(forcats)library(dplyr)library(ggplot2)library(patchwork)
# Match the printed width on this page.options(width = 80)set.seed(42)dir.create("outputs", showWarnings = FALSE)
cell_labels <- c( "Naive CD4 T", "Memory CD4 T", "CD8 T", "B", "NK", "CD14 Mono", "FCGR3A Mono", "DC", "Platelet")cells <- tibble( cell_type = factor(sample( cell_labels, 300, replace = TRUE, prob = c(0.26, 0.17, 0.10, 0.13, 0.05, 0.18, 0.06, 0.03, 0.02) )))gene_fc <- tibble( gene = c("TP53", "BRCA1", "EGFR", "MYC", "KRAS", "PTEN", "RB1", "APC"), log2fc = c(3.2, -2.1, 1.5, 4.8, -0.3, -3.5, 1.1, 2.7))levels(cells$cell_type)[1] "B" "CD14 Mono" "CD8 T" "DC" "FCGR3A Mono"[6] "Memory CD4 T" "Naive CD4 T" "NK" "Platelet"Create a factor
Section titled “Create a factor”factor() and fct()
Section titled “factor() and fct()”factor() sorts the levels. fct() keeps them in the order they first appear.
doses <- c("low", "high", "control", "low")factor(doses)fct(doses)[1] low high control lowLevels: control high low[1] low high control lowLevels: low high controlfct() catches a value outside the levels
Section titled “fct() catches a value outside the levels”factor() turns a value outside levels into NA without a word, so a typo such as Low
becomes missing data. fct() stops and names the value.
factor(c("low", "Low"), levels = c("control", "low", "high"))tryCatch( fct(c("low", "Low"), levels = c("control", "low", "high")), error = \(e) cat(conditionMessage(e), sep = "\n"))[1] low <NA>Levels: control low highAll values of `x` must appear in `levels` or `na`ℹ Missing level: "Low"Set the order
Section titled “Set the order”fct_relevel()
Section titled “fct_relevel()”Name the levels in the order you want. Levels you leave out keep their order after the
ones you name, so fct_relevel(dose, "control") only sets the reference level.
dose <- factor(c("low", "high", "control", "high", "control", "low"))fct_relevel(dose, "control", "low", "high") |> levels()fct_relevel(dose, "control") |> levels()[1] "control" "low" "high"[1] "control" "high" "low"Chromosomes in natural order
Section titled “Chromosomes in natural order”fct_relevel() also takes a function of the current levels. str_sort(numeric = TRUE) puts
chr2 before chr10.
chrom <- factor(c("chr10", "chr2", "chrX", "chr1", "chr2"))levels(chrom)fct_relevel(chrom, \(x) stringr::str_sort(x, numeric = TRUE)) |> levels()[1] "chr1" "chr10" "chr2" "chrX"[1] "chr1" "chr2" "chr10" "chrX"fct_reorder()
Section titled “fct_reorder()”fct_reorder() orders the levels by a second variable. With several values per level, as
in a boxplot, it uses their median unless you set .fun. .desc = TRUE reverses the
order.
gene_fc |> mutate(gene = fct_reorder(gene, log2fc)) |> pull(gene) |> levels()[1] "PTEN" "BRCA1" "KRAS" "RB1" "EGFR" "APC" "TP53" "MYC"The figure draws the same bars in the default order and after fct_reorder(). ggplot2 turns
a character column into a factor with alphabetical levels, which is why the left panel
starts at APC.
up_down <- c(down = "#2a78d6", up = "#e34948")p_default <- ggplot(gene_fc, aes(x = gene, y = log2fc)) + geom_col(aes(fill = if_else(log2fc > 0, "up", "down")), width = 0.7) + labs(title = "Default: alphabetical", x = NULL, y = "log2 fold change")p_sorted <- gene_fc |> mutate(gene = fct_reorder(gene, log2fc)) |> ggplot(aes(x = gene, y = log2fc)) + geom_col(aes(fill = if_else(log2fc > 0, "up", "down")), width = 0.7) + labs(title = "fct_reorder(gene, log2fc)", x = NULL, y = NULL)reorder_plot <- (p_default | p_sorted) & scale_fill_manual(values = up_down, guide = "none") & geom_hline(yintercept = 0, colour = "grey40", linewidth = 0.3) & theme_minimal(base_size = 11) & theme( panel.grid.major.x = element_blank(), panel.grid.minor = element_blank() )ggsave( "outputs/forcats-reorder.png", reorder_plot, width = 8, height = 3.2, dpi = 150, bg = "white")
fct_infreq()
Section titled “fct_infreq()”fct_infreq() orders the levels from the most common to the least common.
cells |> mutate(cell_type = fct_infreq(cell_type)) |> pull(cell_type) |> levels()[1] "Naive CD4 T" "Memory CD4 T" "CD14 Mono" "B" "CD8 T"[6] "NK" "FCGR3A Mono" "DC" "Platelet"fct_inorder()
Section titled “fct_inorder()”fct_inorder() keeps the order of first appearance, such as the row order of a sample
sheet.
samples <- c("S10", "S2", "S1", "S2")levels(factor(samples))levels(fct_inorder(samples))[1] "S1" "S10" "S2"[1] "S10" "S2" "S1"Change the levels
Section titled “Change the levels”fct_recode()
Section titled “fct_recode()”fct_recode() takes new = old pairs and keeps the level order. Quote a new name that has a
space or starts with a digit.
dose |> fct_recode(vehicle = "control", "10 nM" = "low", "100 nM" = "high") |> levels()[1] "vehicle" "100 nM" "10 nM"fct_collapse()
Section titled “fct_collapse()”fct_collapse() merges levels into groups. other_level names the group for every level
you do not list.
cells |> mutate(lineage = fct_collapse( cell_type, Lymphoid = c("Naive CD4 T", "Memory CD4 T", "CD8 T", "NK", "B"), Myeloid = c("CD14 Mono", "FCGR3A Mono", "DC"), other_level = "Other" )) |> count(lineage)# A tibble: 3 × 2 lineage n <fct> <int>1 Lymphoid 2282 Myeloid 683 Other 4fct_lump_n() and fct_lump_min()
Section titled “fct_lump_n() and fct_lump_min()”fct_lump_n() keeps the n most common levels and pools the rest into Other.
cells |> mutate(cell_type = fct_lump_n(cell_type, n = 4)) |> count(cell_type)# A tibble: 5 × 2 cell_type n <fct> <int>1 B 362 CD14 Mono 483 Memory CD4 T 554 Naive CD4 T 835 Other 78fct_lump_min() keeps every level with at least min cells.
cells |> mutate(cell_type = fct_lump_min(cell_type, min = 20)) |> count(cell_type)# A tibble: 7 × 2 cell_type n <fct> <int>1 B 362 CD14 Mono 483 CD8 T 334 Memory CD4 T 555 Naive CD4 T 836 NK 217 Other 24A frequency bar chart with Other last
Section titled “A frequency bar chart with Other last”Lump, sort by frequency, send Other to the end with after = Inf, then reverse. ggplot2
draws the first level of a horizontal axis at the bottom, so fct_rev() puts the largest
group on top.
cell_plot <- cells |> mutate( cell_type = cell_type |> fct_lump_n(n = 6) |> fct_infreq() |> fct_relevel("Other", after = Inf) |> fct_rev() ) |> ggplot(aes(y = cell_type)) + geom_bar(fill = "#2a78d6", width = 0.7) + geom_text( aes(label = after_stat(count)), stat = "count", hjust = -0.3, size = 3.4, colour = "grey20" ) + scale_x_continuous(expand = expansion(mult = c(0, 0.1))) + labs(x = "Cells", y = NULL) + theme_minimal(base_size = 11) + theme( panel.grid.major.y = element_blank(), panel.grid.minor = element_blank() )ggsave( "outputs/forcats-cell-types.png", cell_plot, width = 6, height = 3.4, dpi = 150, bg = "white")
Unused and missing levels
Section titled “Unused and missing levels”fct_drop()
Section titled “fct_drop()”A filter removes rows but keeps every level, so the empty levels still appear in table()
and in a plot with drop = FALSE. fct_drop() removes them.
t_cells <- cells |> filter(cell_type %in% c("Naive CD4 T", "Memory CD4 T", "CD8 T"))nlevels(t_cells$cell_type)nlevels(fct_drop(t_cells$cell_type))[1] 9[1] 3fct_na_value_to_level()
Section titled “fct_na_value_to_level()”NA is not a level, so levels() and table() leave it out. fct_na_value_to_level()
makes it a level that you can name, order, and color. It replaced fct_explicit_na(), which
forcats 1.0 deprecated.
batch <- factor(c("B1", "B2", NA, "B1", NA))fct_na_value_to_level(batch, level = "unknown")[1] B1 B2 unknown B1 unknownLevels: B1 B2 unknownSee also
Section titled “See also”- Data Structures introduces factors, their
levels, and
table()counts per level. - The ggplot2 cheatsheet covers the plots whose order these functions control.
- Publication Figures builds complete figures, from a two group box plot to a clustered heatmap, in R and Python.
- The stringr cheatsheet has
str_sort()and the string functions thatfct_relabel()can apply to every level.
Scientific references
Section titled “Scientific references”The forcats package by Wickham supplies tools for categorical variables.
Further reading
Section titled “Further reading”-
The guide compares frequency order, explicit level order, rare-level groups and missing factor values.