Skip to content

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.

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"

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 low
Levels: control high low
[1] low high control low
Levels: low high control

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 high
All values of `x` must appear in `levels` or `na`
ℹ Missing level: "Low"

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"

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() 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"
)

Two bar charts of log2 fold change for eight genes. On the left the genes run alphabetically from APC to TP53, and the blue down bars for BRCA1, KRAS, and PTEN sit between red up bars. On the right fct_reorder sorts them from PTEN at -3.5 through BRCA1 and KRAS to MYC at 4.8, so the three blue bars come first and the five red bars rise to the right.

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() 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"

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() 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 228
2 Myeloid 68
3 Other 4

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 36
2 CD14 Mono 48
3 Memory CD4 T 55
4 Naive CD4 T 83
5 Other 78

fct_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 36
2 CD14 Mono 48
3 CD8 T 33
4 Memory CD4 T 55
5 Naive CD4 T 83
6 NK 21
7 Other 24

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"
)

Horizontal bar chart of cell counts for 300 simulated PBMCs. From the top the bars read Naive CD4 T 83, Memory CD4 T 55, CD14 Mono 48, B 36, CD8 T 33, and NK 21. The pooled Other bar, 24 cells, sits at the bottom even though it is larger than NK.

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] 3

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 unknown
Levels: B1 B2 unknown
  • 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 that fct_relabel() can apply to every level.

The forcats package by Wickham supplies tools for categorical variables.

  • forcats introduction

    The guide compares frequency order, explicit level order, rare-level groups and missing factor values.