- Published on
- Updated 17 min read
Differential gene expression with DESeq2: a step-by-step tutorial

- Authors

- Name
- BioTech Bench
Table of contents
- What you'll learn
- Setup and installation
- The experiment: paired human airway smooth muscle cells
- Step 1: Build the DESeqDataSet and choose the right design formula
- Step 2: Fit the DESeq2 model and inspect sample QC
- Step 3: Extract and understand the results table
- Step 4: Shrink noisy fold changes with apeglm and filter hits
- Step 5: Plot donor-level counts and verify known biology
- Honest limitations and common DESeq2 mistakes
- My take
- Resources
This is Arc 3, Part 14 of the R for Biologists series.
Look at the count matrix sitting on your screen after an RNA-seq alignment run: sixty thousand rows of Ensembl gene IDs, eight sample columns of raw integers, and a lab meeting forty-eight hours away where everyone wants to know which pathways your drug actually moved.
The tempting shortcut is to normalize each column to counts per million and loop a Student's t-test down all 60,000 rows. As we saw in understanding RNA-seq count matrices and multiple testing correction in R, that shortcut fails twice. First, sequencing counts are discrete and skewed — low-count genes have huge relative sampling noise while high-count genes show biological overdispersion that violates normal t-test assumptions. Second, with only three or four biological replicates per condition, per-gene variance estimates are wildly unstable on their own: by random luck, three numbers occasionally land almost identically and produce a tiny standard error and a fake 10^-8 p-value.
DESeq2 solves both problems by modeling raw integer counts directly with a Negative Binomial generalized linear model and sharing information across all expressed genes to stabilize dispersion and fold-change estimates. In this tutorial, we'll run a complete, publication-grade DESeq2 workflow on a real human primary-cell experiment — including the sample QC, paired-donor modeling, and log2 fold-change shrinkage steps that short tutorials usually skip.
What you'll learn
- How to align raw integer counts and sample
colDatainside aDESeqDataSetwithout sample-swap bugs - Why modeling donor pairing (
~ cell + dex) recovers hundreds of real differentially expressed genes that an unpaired design misses - How to run variance-stabilizing transformation (
vst) and PCA before trusting any p-value - What
DESeq()actually computes under the hood: size factors, empirical Bayes dispersion shrinkage, and Wald testing - Why unshrunk
log2FoldChangeexaggerates noisy low-count genes, and howlfcShrink(..., type = "apeglm")fixes gene rankings - How to plot individual donor trajectories and sanity-check results against known glucocorticoid biology (and housekeeping myths)
Setup and installation
DESeq2, apeglm (for fold-change shrinkage), and airway (our real RNA-seq dataset) live on Bioconductor. Install them once with BiocManager, alongside ggplot2 for custom QC plots:
if (!requireNamespace("BiocManager", quietly = TRUE))
install.packages("BiocManager")
BiocManager::install(c("DESeq2", "airway", "apeglm"))
install.packages("ggplot2")
Load the packages for our session:
library(DESeq2)
library(airway)
library(apeglm)
library(ggplot2)
Every output and figure in this post was generated by running the exact code shown in R 4.5.3 with DESeq2 1.50.2, airway 1.30.0, and apeglm 1.32.0. Minor Bioconductor point releases can shift the last decimal place slightly.
The experiment: paired human airway smooth muscle cells
The airway package packages the RNA-seq counts from Himes et al. (2014). Primary human airway smooth muscle cell cultures from four distinct human donors (N61311, N052611, N080611, and N061011) were each split into two flasks: one left untreated (untrt) and one treated for 18 hours with dexamethasone (trt), a synthetic glucocorticoid prescribed to suppress airway inflammation in asthma.
Load the dataset and inspect the raw count matrix:
data("airway")
counts <- assay(airway)
dim(counts)
[1] 63677 8
That gives 63,677 Ensembl gene annotations (rows) across 8 sequencing libraries (columns). Each entry is the raw integer count of paired-end fragments uniquely assigned to that gene — never feed FPKM, TPM, or pre-normalized decimals into DESeq2, because its noise model depends on knowing whether a value of 5 came from 5 actual reads or 5,000 reads scaled down.
Now extract the sample metadata table (coldata) and explicitly set untreated (untrt) as the reference level:
coldata <- as.data.frame(colData(airway))[, c("cell", "dex")]
coldata$dex <- relevel(coldata$dex, ref = "untrt")
coldata
cell dex
SRR1039508 N61311 untrt
SRR1039509 N61311 trt
SRR1039512 N052611 untrt
SRR1039513 N052611 trt
SRR1039516 N080611 untrt
SRR1039517 N080611 trt
SRR1039520 N061011 untrt
SRR1039521 N061011 trt
Why bother with relevel(coldata$dex, ref = "untrt")? Because R orders factor levels alphabetically by default! Alphabetically, "trt" comes before "untrt", which would make treated cells the denominator and flip the sign of every single log2 fold change in your paper. Setting ref = "untrt" guarantees that positive log2FoldChange means upregulated by dexamethasone.
Pre-filtering unexpressed genes
Roughly three-quarters of those 63,677 Ensembl rows are non-coding transcripts, pseudogenes, or tissue-restricted genes with zero or one read in smooth muscle. Removing genes that aren't meaningfully expressed shrinks memory use, speeds up model fitting, and avoids cluttering diagnostic plots. A clean, standard rule is to keep genes with at least 10 counts in at least k samples, where k is the size of your smallest experimental group (here, 4 samples):
keep <- rowSums(counts >= 10) >= 4
counts <- counts[keep, ]
nrow(counts)
[1] 16139
We are down to 16,139 expressed genes — right in the typical 12,000–17,000 range for a single human cell type.
Step 1: Build the DESeqDataSet and choose the right design formula
Now bundle the filtered counts, sample table, and experimental design formula into a DESeqDataSet:
dds <- DESeqDataSetFromMatrix(countData = counts,
colData = coldata,
design = ~ cell + dex)
Pause on design = ~ cell + dex, because the design formula is the single highest-leverage decision in differential expression analysis.
Primary human donors vary substantially in baseline gene expression due to age, genetics, and passage history. If you wrote design = ~ dex, DESeq2 would treat all four untreated flasks as interchangeable replicates and dump every donor-to-donor difference into the residual error term. Writing ~ cell + dex fits an additive baseline offset for each donor (cell) and estimates the dexamethasone effect (dex) within each donor pair. Always put covariates/blocking factors (cell, batch, sex) first and the primary condition of interest (dex) last so results(dds) pulls the treatment contrast automatically.
How much difference does accounting for donor pairing actually make on this exact dataset? If we fit ~ dex instead of ~ cell + dex on these same 16,139 genes, the number of significant hits at padj < 0.05 drops from 4,077 down to 2,766 (and from 938 down to 795 at |log2FC| > 1). Modeling your experimental design properly rescues over 1,300 real dexamethasone-responsive genes for free!
Step 2: Fit the DESeq2 model and inspect sample QC
Run the full estimation and testing pipeline with DESeq():
dds <- DESeq(dds)
estimating size factors
estimating dispersions
gene-wise dispersion estimates
mean-dispersion relationship
final dispersion estimates
fitting model and testing
Under that six-line status message, three distinct statistical steps just happened:
- Median-of-ratios size factors (
sizeFactors(dds)): Instead of dividing by total read count (which gets skewed if a handful of super-abundant genes double in treated cells), DESeq2 computes each gene's geometric mean across samples, takes the median ratio per library, and scales around1.0:
round(sizeFactors(dds), 4)
SRR1039508 SRR1039509 SRR1039512 SRR1039513 SRR1039516 SRR1039517 SRR1039520
1.0220 0.8961 1.1740 0.6684 1.1754 1.3993 0.9165
SRR1039521
0.9451
Notice SRR1039513 (0.6684) versus SRR1039517 (1.3993): one library was sequenced more than twice as deeply as the other, and DESeq2 accounts for that directly as an offset inside the Generalized Linear Model rather than rounding normalized counts.
- Sample-level PCA after Variance-Stabilizing Transformation (
vst): Before looking at p-values, always run Principal Component Analysis (PCA) to verify that samples cluster as expected and nobody swapped tubes at the bench. Raw counts can't go straight into PCA because the highest-count genes dominate Euclidean distance, and plainlog2(counts + 1)inflates Poisson noise in low-count genes.vst()flattens variance across the expression range specifically for PCA and clustering:
vsd <- vst(dds, blind = FALSE)
pca_data <- plotPCA(vsd, intgroup = c("dex", "cell"), returnData = TRUE)
percent_var <- round(100 * attr(pca_data, "percentVar"))
ggplot(pca_data, aes(x = PC1, y = PC2, color = dex, shape = cell)) +
geom_point(size = 4) +
scale_color_manual(
values = c("untrt" = "#475569", "trt" = "#0284c7"),
labels = c("untrt" = "Untreated", "trt" = "Dexamethasone")
) +
labs(
title = "PCA of airway RNA-seq samples (VST-transformed counts)",
x = paste0("PC1: ", percent_var[1], "% variance"),
y = paste0("PC2: ", percent_var[2], "% variance"),
color = "Treatment",
shape = "Donor"
) +
theme_bw(base_size = 12)

Figure 1. Principal Component Analysis of VST-transformed counts across the 8 airway libraries. PC1 (48% of variance) separates untreated (grey) from dexamethasone-treated (blue) flasks cleanly, while PC2 (24% of variance) reflects baseline donor identity — each donor shifts right by almost the exact same vector upon treatment. Output of the code above.
Figure 1 is a textbook justification for ~ cell + dex: donor N080611 (squares at the top) sits far above the other three donors on PC2, yet its horizontal treatment shift along PC1 matches the other three donors cleanly.
- Empirical Bayes dispersion shrinkage (
plotDispEsts): In the Negative Binomial model, a gene's count variance is , where is the dispersion (squared biological coefficient of variation: means biological variability between replicates). With 8 samples, single-gene estimates of (black dots) scatter widely, so DESeq2 fits a smooth trend line across expression levels (red curve) and shrinks noisy estimates toward it (blue dots), while leaving true high-variance biological outliers unshrunk (blue circles around black dots at the top):
plotDispEsts(dds, main = "DESeq2 dispersion estimates across 16,139 airway genes")

Figure 2. Dispersion-by-mean diagnostic plot (plotDispEsts). Dispersion decreases smoothly as mean read count rises and settles near 0.01–0.05 at high counts, confirming clean biological replicates without batch-driven variance blowup. Output of the code above.
Step 3: Extract and understand the results table
Extract the Wald test results for the last variable in our design formula (dex):
res <- results(dds)
res
log2 fold change (MLE): dex trt vs untrt
Wald test p-value: dex trt vs untrt
DataFrame with 16139 rows and 6 columns
baseMean log2FoldChange lfcSE stat pvalue padj
<numeric> <numeric> <numeric> <numeric> <numeric> <numeric>
ENSG00000000003 710.0340 -0.3852374 0.100566 -3.830691 1.27784e-04 9.42586e-04
ENSG00000000419 521.2139 0.2028550 0.111494 1.819425 6.88466e-02 1.80923e-01
ENSG00000000457 237.6016 0.0339708 0.141191 0.240601 8.09864e-01 9.03973e-01
ENSG00000000460 58.0405 -0.0935336 0.279744 -0.334354 7.38112e-01 8.63041e-01
ENSG00000000971 5827.0185 0.4224097 0.089135 4.738988 2.14788e-06 2.35644e-05
... ... ... ... ... ... ...
ENSG00000273382 18.20503 -0.7353004 0.469498 -1.566143 0.117315 0.268463
ENSG00000273448 14.03190 0.0570817 0.483988 0.117940 0.906115 0.952999
ENSG00000273472 11.08682 -0.4100271 0.558793 -0.733772 0.463087 NA
ENSG00000273486 15.48211 -0.1530205 0.471757 -0.324363 0.745663 0.866737
ENSG00000273487 8.17522 1.0397146 0.679153 1.530898 0.125795 NA
Every column in res tells a specific piece of the story:
baseMean: Mean of size-factor-normalized counts across all 8 samples (gives you a sense of expression abundance, though not normalized for gene length).log2FoldChange: Maximum-likelihood estimate of .+1means doubled (),+3means higher, and-2means reduced to one quarter ().lfcSE: Standard error of thatlog2FoldChangeestimate. Compare row 5 (baseMean = 5827,lfcSE = 0.089) with the last row (baseMean = 8.2,lfcSE = 0.679): low-count genes carry huge fold-change uncertainty.stat: Wald test statistic (log2FoldChange / lfcSE).pvalue: Unadjusted two-sided Wald p-value. Never use this column directly as your significance cutoff.padj: Benjamini-Hochberg False Discovery Rate (FDR) adjusted p-value. Why areENSG00000273472andENSG00000273487NAinpadj? Because DESeq2's independent filtering noticed that genes withbaseMean < 12had virtually zero chance of passing significance, so excluding those 626 ultra-low genes from the BH multiple-testing denominator boosted statistical power on the remaining 15,513 genes! (If a single sample ever has an extreme Cook's distance spike, DESeq2 also flags bothpvalueandpadjasNAto protect you from single-sample outliers.)
Check the high-level tally with summary(res):
summary(res)
out of 16139 with nonzero total read count
adjusted p-value < 0.1
LFC > 0 (up) : 2607, 16%
LFC < 0 (down) : 2298, 14%
outliers [1] : 0, 0%
low counts [2] : 626, 3.9%
(mean count < 12)
[1] see 'cooksCutoff' argument of ?results
[2] see 'independentFiltering' argument of ?results
Step 4: Shrink noisy fold changes with apeglm and filter hits
First, attach human-readable HGNC gene symbols from rowData(airway) and filter to genes passing both statistical confidence (padj < 0.05) and biological magnitude (|log2FoldChange| > 1, at least a 2-fold change). Always wrap row indexing in which() so NA values in padj don't inject empty NA rows into your table:
res$symbol <- rowData(airway)[rownames(res), "gene_name"]
res_df <- as.data.frame(res)
sig_genes <- res_df[which(res_df$padj < 0.05 & abs(res_df$log2FoldChange) > 1), ]
sig_genes <- sig_genes[order(sig_genes$padj), ]
nrow(sig_genes)
[1] 938
table(sig_genes$log2FoldChange > 0)
FALSE TRUE
450 488
938 genes pass both cutoffs (488 upregulated, 450 downregulated). Here are the top 10 ranked by padj:
head(sig_genes[, c("symbol", "baseMean", "log2FoldChange", "padj")], 10)
symbol baseMean log2FoldChange padj
ENSG00000152583 SPARCL1 997.9612 4.570944 5.530127e-132
ENSG00000165995 CACNB2 495.5675 3.287083 5.530127e-132
ENSG00000120129 DUSP1 3411.9661 2.943859 1.248569e-124
ENSG00000101347 SAMHD1 12712.9456 3.763021 2.909302e-124
ENSG00000189221 MAOA 2343.5733 3.349721 3.538038e-119
ENSG00000211445 GPX3 12298.1966 3.726415 1.344901e-106
ENSG00000157214 STEAP2 3012.8580 1.972783 3.955210e-101
ENSG00000162614 NEXN 5399.1360 2.031697 1.212676e-96
ENSG00000125148 MT2A 3659.6960 2.207006 1.961381e-91
ENSG00000154734 ADAMTS1 30345.8486 2.341632 4.017702e-85
Why you also want lfcShrink() for ranking and visualization
What happens if a colleague sorts res_df by log2FoldChange instead of padj to pick candidates for GSEA pathway enrichment or MA plots? Unshrunk maximum-likelihood fold changes treat 0 reads vs 8 reads as an enormous fold change even when lfcSE is huge.
Check the exact coefficient names in our model with resultsNames(dds) and apply lfcShrink() using apeglm (Zhu et al., 2019), which shrinks noisy high-SE estimates toward zero while leaving well-supported large fold changes intact:
resultsNames(dds)
[1] "Intercept" "cell_N061011_vs_N052611"
[3] "cell_N080611_vs_N052611" "cell_N61311_vs_N052611"
[5] "dex_trt_vs_untrt"
res_shrunk <- lfcShrink(dds, coef = "dex_trt_vs_untrt", type = "apeglm")
Note that lfcShrink() refines effect sizes (log2FoldChange and lfcSE) for ranking, MA plots, and heatmaps — it does not alter the Wald pvalue or padj from results(dds). Use res (or res_shrunk, which carries the same padj) for significance calls, and always feed shrunk LFCs when ranking genes by fold change.
Step 5: Plot donor-level counts and verify known biology
Never stop at a summary table without plotting individual sample counts for your headline hits! Let's check seven canonical glucocorticoid-receptor targets first:
known <- c("FKBP5", "TSC22D3", "PER1", "KLF15", "ZBTB16", "DUSP1", "CRISPLD2")
res_df[res_df$symbol %in% known, c("symbol", "baseMean", "log2FoldChange", "padj")]
symbol baseMean log2FoldChange padj
ENSG00000096060 FKBP5 2566.3214 4.042655 7.296620e-26
ENSG00000103196 CRISPLD2 3085.0222 2.627280 1.563223e-45
ENSG00000109906 ZBTB16 385.2007 7.348689 2.670503e-40
ENSG00000120129 DUSP1 3411.9661 2.943859 1.248569e-124
ENSG00000157514 TSC22D3 2207.5036 3.186160 3.177825e-19
ENSG00000163884 KLF15 561.4144 4.455334 7.653841e-78
ENSG00000179094 PER1 777.0989 3.187775 1.828073e-81
Every single canonical glucocorticoid target surges strongly — from 6.2-fold (CRISPLD2, the focal discovery of Himes et al. 2014) up to more than 160-fold (ZBTB16, ). Let's pull the normalized counts for FKBP5 (ENSG00000096060) with plotCounts(..., returnData = TRUE) and draw lines connecting each donor's untreated and treated flasks:
fkbp5_counts <- plotCounts(dds, gene = "ENSG00000096060", intgroup = c("dex", "cell"), returnData = TRUE)
fkbp5_counts
count dex cell
SRR1039508 254.9090 untrt N61311
SRR1039509 5192.0495 trt N61311
SRR1039512 325.0373 untrt N052611
SRR1039513 5798.2020 trt N052611
SRR1039516 511.8292 untrt N080611
SRR1039517 3926.1427 trt N080611
SRR1039520 168.5275 untrt N061011
SRR1039521 4357.8737 trt N061011
ggplot(fkbp5_counts, aes(x = dex, y = count, group = cell, color = cell)) +
geom_line(linewidth = 0.9, alpha = 0.8) +
geom_point(size = 3.5) +
scale_y_log10() +
scale_x_discrete(labels = c("untrt" = "Untreated", "trt" = "Dexamethasone")) +
labs(
title = "FKBP5 normalized counts across paired donors",
subtitle = "ENSG00000096060 (log2FC = 4.04, padj = 7.3e-26)",
x = NULL,
y = "Normalized counts (log10 scale)",
color = "Donor"
) +
theme_bw(base_size = 12)

Figure 3. Paired normalized read counts for glucocorticoid cochaperone FKBP5 across all four human donors. Every donor increases more than 7-fold to 25-fold upon dexamethasone exposure, ruling out single-sample outlier artifacts. Output of the code above.
Now check three genes that trip up wet-lab assumptions all the time:
res_df[res_df$symbol %in% c("GAPDH", "ACTB", "IL6"), c("symbol", "baseMean", "log2FoldChange", "padj")]
symbol baseMean log2FoldChange padj
ENSG00000075624 ACTB 74706.8236 0.8843404 0.00776483
ENSG00000111640 GAPDH 26404.0276 -0.1578141 0.38296769
ENSG00000136244 IL6 112.5747 -0.7545924 0.05614557
Look at how much real bench wisdom sits inside those three rows:
GAPDHstays flat (log2FC = -0.16,padj = 0.38).ACTB(beta-actin) increases 1.85-fold (log2FC = +0.88,padj = 0.0078) because dexamethasone remodels the actin cytoskeleton in smooth muscle cells! If you ran follow-up qPCR with ΔΔCt normalized only toACTB, every single target gene on your plate would be biased downward by nearly two-fold.IL6trends downward (log2FC = -0.75) but misses significance (padj = 0.056), because resting smooth muscle cells weren't stimulated with TNF or LPS first — you can't strongly suppress baseline inflammation that wasn't switched on.
Honest limitations and common DESeq2 mistakes
DESeq2 is extraordinarily reliable when used as designed, and quietly misleading when its assumptions are broken:
- Technical replicates must be collapsed, never treated as columns. If you sequenced the same library across two flow-cell lanes, sum them with
collapseReplicates()before callingDESeq(). Leaving technical replicates as separate columns tricks DESeq2 into thinking biological dispersion is near zero and produces thousands of false positives. - Global transcriptome shifts break median-of-ratios normalization. DESeq2 assumes most genes are NOT changing. In synthetic spike-in experiments, global transcription-shutdown treatments (flavopiridol, Pol II degrons), or severe chromatin-modifier knockouts where 70% of mRNAs drop together, standard
estimateSizeFactors()scales away the global drop unless you supply exogenous ERCC/spike-incontrolGenes. baseMeancannot compare expression between two different genes. BecauseDESeq2does not divide by transcript length, a 10 kb gene will have a much largerbaseMeanthan an equally transcribed 1 kb gene.DESeq2only compares each gene against itself across conditions (where length cancels out unless isoform usage switches, in which case import transcript-level abundances viatximport).- Very large cohorts (
n > 30–50per group) have simpler alternatives. In large clinical RNA-seq cohorts, Negative Binomial GLMs can become slightly anti-conservative if outliers or unmodeled covariates creep in;limma-voomor Wilcoxon rank-sum tests often calibrate FDR better at biobank scale.
My take
Whenever someone hands me a bulk RNA-seq count matrix with 3 to 15 biological replicates per group, DESeq2 is still the first tool I open — provided three non-negotiable habits stay glued to the script: plot VST PCA before looking at p-values, include known batch/donor blocking variables in design, and plot plotCounts() on your top hits before ordering antibodies or qPCR primers.
In Part 15, we'll run edgeR on this exact same airway matrix to see where the two flagship Bioconductor callers agree and where they diverge.
What's the trickiest experimental design formula you've had to set up in DESeq2 — paired donors, multiple timepoints, or an interaction term? Drop a comment below.
Resources
| Resource | What it covers | Link |
|---|---|---|
| DESeq2 Bioconductor Vignette | Official comprehensive workflow by Love, Anders, and Huber | bioconductor.org/packages/DESeq2 |
| Love, Huber & Anders (2014) | Original DESeq2 methods paper (Genome Biology, 15:550) | doi:10.1186/s13059-014-0550-8 |
| Zhu, Ibrahim & Love (2019) | apeglm heavy-tailed LFC shrinkage paper (Bioinformatics, 35:2084) | doi:10.1093/bioinformatics/bty895 |
| Himes et al. (2014) | Primary airway dexamethasone RNA-seq study (PLOS ONE, 9:e99625) | doi:10.1371/journal.pone.0099625 |
| airway Data Package | Bioconductor RangedSummarizedExperiment dataset used above | bioconductor.org/packages/airway |
Keep reading
Your first single-cell RNA-seq analysis in R with Seurat
Cell Ranger just handed you three files — matrix.mtx, genes.tsv, and barcodes.tsv — and a matrix that is 93% zeros. Here is how to take a real 10x Genomics dataset from raw UMI counts to an annotated UMAP of human immune cell types in R with Seurat v5.
Volcano plots and MA plots: visualizing RNA-seq results in R
Your DESeq2 results table has thousands of rows, and sorting it in Excel tells you almost nothing about your experiment. Here is how to build volcano plots and MA plots in R with ggplot2 — and how to read what they are actually telling you.
Gene ontology and pathway enrichment analysis in R with clusterProfiler
You ran DESeq2 and got your list of differentially expressed genes. Now what? Here is how to use clusterProfiler to find out which biological pathways are actually changing in your experiment — with real code, real output, and real plots.