From Raw Counts to Differential Expression

You've run DESeq2 once. Now let's open the box: how to set up the right comparison with a design formula, what DESeq2 actually does to your counts, and how to read every column of the results table with confidence.

๐ŸŸก Intermediate โฑ๏ธ ~1.5 hours ๐Ÿ“Š R ยท DESeq2 ๐ŸŒ Runs free in Colab

Before you start

  • You've done the flagship Your First RNA-seq Analysis, so the five-step workflow is familiar.
  • You can read a little R. (New to R? Start with the R series.)
  • You do not need the heavy statistics. We'll explain the ideas in plain language and point at the math without drowning in it.

Learning objectives

By the end of this lesson you will be able to: load a count matrix and sample table into DESeq2 in R, run the standard differential-expression workflow with a design formula (such as ~ condition, or ~ cell + dex for a paired design), and interpret the results table including log2 fold change and adjusted p-values.

Where we left off

In the flagship project you took a count matrix and a metadata table, ran two lines of DESeq2, and got a results table plus a volcano plot. That was the speed run. This lesson slows down and answers the questions that actually make you good at this: what is the design formula doing, what happens inside DESeq(), and how do I trust the numbers that come out?

โ–ถ Code along in Google Colab

Set the runtime to R (Runtime, then Change runtime type, then R), and run each block as you read. The DESeq2 install takes about 3 to 5 minutes the first time, which is completely normal and only happens once per session.

Open the R notebook in Colab โ†’

1The design formula: the most important line you'll write

The design formula is how you tell DESeq2 what comparison you care about. The simplest version names a single column of your sample table:

design = ~ dex

The tilde (~) means "model the counts as a function of...", and dex is the column that splits the samples into groups (here, untreated and dexamethasone-treated airway cells). That one choice frames the whole analysis.

Real experiments are rarely that clean. In the airway data, the 8 samples come from 4 different donors, and donors differ from each other naturally. In the flagship lesson you already told DESeq2 to account for that:

design = ~ cell + dex

This says: "test the effect of dex while holding cell (the donor) constant." The same idea works for a processing batch, for example ~ batch + condition. (The order of the terms does not change the estimates. By convention the variable you care about goes last, because results() reports the last variable by default.) A simple rule worth memorizing: the variable you actually want to test goes last, and anything you want to control for (batch, sex, age) goes before it.

Decode the jargonBatch effect

A "batch" is simply a group of samples that were handled together: prepared on the same day, by the same person, or on the same machine. When different batches pick up small technical differences that have nothing to do with the biology, that is a batch effect. Left alone it can masquerade as a real result, so adding batch to the design tells DESeq2 to subtract those technical differences out before testing your real question.

Decode the jargonDesign formula

A short recipe that lists which sample features should be modeled. ~ dex tests one factor. ~ cell + dex (or ~ batch + dex) accounts for the donor or batch while testing treatment, so the result reflects biology rather than which donor or which day a sample came from. Getting this right is often the difference between a real finding and an artifact.

2What DESeq2 actually does (three moves)

When you call DESeq(dds), three things happen in sequence. You don't have to do them by hand, but knowing what they are makes the results make sense.

Move 1: Normalization (size factors). Some samples are sequenced more deeply than others, so every gene in them looks "higher" just by accident. DESeq2 computes a size factor per sample and divides it out, so counts become comparable across samples. This corrects for sequencing depth and for differences in library composition between samples (it does not correct for gene length, which is fine because differential expression compares the same gene across samples). Correcting for composition, not just total counts, is exactly why DESeq2 size factors differ from naive total-count scaling.

Move 2: Dispersion estimation. With only a few replicates per group, the per-gene variability is hard to estimate. DESeq2 borrows strength across all genes: it looks at how variable genes are at each expression level and shrinks each gene's noisy estimate toward that trend. This is why DESeq2 works well even with three replicates, where naive methods fall apart.

Move 3: Model and test. DESeq2 fits a negative binomial model (the right shape for count data) and, for each gene, runs a statistical test asking whether the difference between groups is bigger than the noise. Out comes a log2FoldChange, a pvalue, and an adjusted p-value.

Decode the jargonDispersion

A number that captures how much a gene's counts bounce around between replicates of the same group, beyond what you'd expect by chance. High dispersion means a noisy gene, so a larger difference is needed before DESeq2 will call it significant. Sharing dispersion information across genes is one of DESeq2's superpowers.

3Run it, with two good habits

Here is the workflow again, with two additions that real analyses use: filtering out genes with almost no reads, and checking the coefficient names.

library(DESeq2)

base <- "https://raw.githubusercontent.com/MennahBassiouny/bionexus/main/"

# Count matrix: rows = genes (Ensembl IDs), columns = the 8 samples
counts  <- as.matrix(read.csv(paste0(base, "airway-counts.csv"), row.names = 1))
# Sample table: which donor (cell) and whether it was treated (dex)
samples <- read.csv(paste0(base, "airway-samples.csv"), row.names = 1)
# Gene names, so results show DUSP1 instead of ENSG00000120129
genes   <- read.csv(paste0(base, "airway-genes.csv"), row.names = 1)

samples$cell <- factor(samples$cell)
samples$dex  <- factor(samples$dex, levels = c("untrt", "trt"))  # untreated = baseline
samples <- samples[colnames(counts), ]   # same order as the count columns

dds <- DESeqDataSetFromMatrix(countData = counts,
                              colData   = samples,
                              design    = ~ cell + dex)

# Habit 1: drop genes with almost no reads (faster, less noise)
keep <- rowSums(counts(dds)) >= 10
dds <- dds[keep, ]

dds <- DESeq(dds)

# Habit 2: see the coefficients DESeq2 estimated (you'll need a name in step 5)
resultsNames(dds)   # ends with "dex_trt_vs_untrt"

4Read the results table properly

Pull the comparison you want, then read what came back:

res <- results(dds, contrast = c("dex", "trt", "untrt"), alpha = 0.05)
summary(res)                                   # how many up / down at padj < 0.05
res$symbol <- genes[rownames(res), "symbol"]   # readable gene names
head(res[order(res$padj), ], 10)               # the 10 most convincing genes

Every column earns its place:

  • baseMean: the average normalized count for that gene across all samples. A sanity check on how expressed the gene is.
  • log2FoldChange: the effect size, on a log2 scale. Plus 1 means doubled in treated vs untreated, minus 1 means halved. Sign is direction, size is magnitude.
  • lfcSE: the standard error of that fold change, so how uncertain it is.
  • stat: the test statistic (the fold change divided by its error).
  • pvalue: the probability of seeing a change at least this large if the gene were truly unchanged.
  • padj: the Benjamini-Hochberg adjusted p-value, which controls the false discovery rate (FDR) across thousands of genes. Use this column, not pvalue, to call hits.

To pull a clean list of hits, filter on both significance and effect size:

# significant AND at least a two-fold change
sig <- subset(res, padj < 0.05 & abs(log2FoldChange) > 1)
nrow(sig)   # about 1,000 genes

One thing that surprises beginners: some genes have NA in the padj column. That is not a bug. padj is NA when DESeq2 filtered a gene out for having counts too low to be likely to reach significance (this "independent filtering" gives your real hits more power), when a gene has zero counts in every sample, or when it has an extreme outlier count. Treat NA padj as "not testable", not "failed". In airway, with the filter from step 3, about 5,200 of the 22,000 remaining genes get NA for low counts.

5Cleaner effect sizes: LFC shrinkage

A low-count gene can show a huge fold change purely from noise (two reads versus eight reads is "4x", but it's meaningless). Shrinkage fixes this: it pulls unreliable fold changes toward zero while leaving well-measured genes almost untouched. The result is rankings you can trust and much cleaner volcano and MA plots.

# apeglm is the recommended shrinkage method; install it once if needed
# BiocManager::install("apeglm")
res_shrunk <- lfcShrink(dds, coef = "dex_trt_vs_untrt", type = "apeglm")
head(res_shrunk[order(res_shrunk$padj), ], 10)

The coef name comes straight from resultsNames(dds) in step 3. Use the shrunken fold changes when you rank genes by fold change or plot fold changes (for example an MA plot). Shrinkage changes only the log2FoldChange column: pvalue and padj are the same in both.

6Save your work

Write the table to a file so you can open it in Excel, share it, or feed it into the next lesson (volcano plots and enrichment both start from this table):

write.csv(as.data.frame(res), "deseq2_results.csv")

๐Ÿ”ถ Try this: test the design

Change the design to ~ dex and rerun steps 3 and 4. You should lose roughly a third of your significant genes (about 2,700 instead of about 4,000). Why? Without cell, the natural differences between the 4 donors are treated as noise, which weakens the evidence for every gene. Then look at resultsNames(dds) for both designs and spot the difference.

Find dataset links in Resources โ†’

The statistics behind that padj column

Why a raw p-value of 0.05 is not enough when you test thousands of genes at once, and what the adjustment actually does, is the subject of Statistics essentials and The multiple-testing problem. You do not need them to finish here, but they are the "why" behind trusting padj over the raw p-value.

Check your understanding

In the design ~ batch + condition, which effect is being tested?
The effect of condition. It comes last, so DESeq2 tests it after accounting for batch. Batch is a control variable here, not the thing being tested.
Why would a gene have NA in its padj column?
Most often because DESeq2 filtered it out for having counts too low to be likely to reach significance (independent filtering). Genes with all-zero counts or an extreme outlier also get NA. Removing those genes from the multiple-testing pool makes your real hits more significant. NA means "not testable", not "failed".
When should you use shrunken (lfcShrink) fold changes?
When you rank or plot by fold change. Shrinkage tames the wild fold changes that low-count genes produce by chance, so fold-change rankings and MA plots reflect well-measured effects. It does not change p-values or padj.
In the airway dataset the design is ~ cell + dex. Which column holds the treatment being tested?
dex is the dexamethasone treatment, and because it is the last term DESeq2 tests its effect after adjusting for the cell line (cell). Putting cell first lets it soak up cell-line differences so the dex effect is cleaner.
Why does DESeq2 need raw integer counts rather than already-normalized values like TPM?
DESeq2 models count noise directly and estimates its own size factors to normalize for depth. Feeding it pre-normalized values like TPM breaks the assumptions its negative-binomial model relies on.

Sources & further reading

  1. Love MI, Huber W, Anders S. Moderated estimation of fold change and dispersion for RNA-seq data with DESeq2. Genome Biology 15: 550, 2014. doi:10.1186/s13059-014-0550-8
  2. Anders S, Huber W. Differential expression analysis for sequence count data. Genome Biology 11: R106, 2010. (DESeq; median-of-ratios size factors) doi:10.1186/gb-2010-11-10-r106
  3. Bourgon R, Gentleman R, Huber W. Independent filtering increases detection power for high-throughput experiments. PNAS 107: 9546-9551, 2010. (why some padj values are NA) doi:10.1073/pnas.0914005107
  4. Li Y, Ge X, Peng F, Li W, Li JJ. Exaggerated false positives by popular differential expression methods when analyzing human population samples. Genome Biology 23: 79, 2022. (a caveat for large human cohorts) doi:10.1186/s13059-022-02648-4
  5. Himes BE, Jiang X, Wagner P, et al. RNA-Seq transcriptome profiling identifies CRISPLD2 as a glucocorticoid responsive gene that modulates cytokine function in airway smooth muscle cells. PLoS One 9: e99625, 2014. (The airway dataset used in this lesson.) doi:10.1371/journal.pone.0099625

Last reviewed: October 2026.

Next in Track 3

Sample QC and PCA for RNA-seq →