DESeq2
DESeq2 fits a negative binomial model to every gene in a count matrix and tests one
coefficient of the design with a Wald test. Every example here runs on the airway
dataset, which holds eight samples of airway smooth muscle cells from four donors. Each
donor was sequenced once untreated and once after dexamethasone. The design is
~ cell + dex, the model the
DESeq2 & pyDESeq2 guide fits, so the
gene counts and p-values on this page match that guide.
Quick reference
Section titled “Quick reference”| Task | Call |
|---|---|
| From a SummarizedExperiment | DESeqDataSet(se, design = ~ cell + dex) |
| From a matrix and sample sheet | DESeqDataSetFromMatrix(counts, coldata, design) |
| From tximport, not run here | DESeqDataSetFromTximport(txi, coldata, design) |
| Prefilter | dds[rowSums(counts(dds)) >= 10, ] |
| Reference level | dds$dex <- relevel(dds$dex, ref = "untrt") |
| Fit | DESeq(dds) |
| Likelihood ratio test | DESeq(dds, test = "LRT", reduced = ~ cell) |
| Coefficient names | resultsNames(dds) |
| Results by name | results(dds, name = "dex_trt_vs_untrt") |
| Results by contrast | results(dds, contrast = c("dex", "trt", "untrt")) |
| Test a fold change threshold | results(dds, lfcThreshold = 1) |
| Shrink fold changes | lfcShrink(dds, coef = "...", type = "apeglm") |
| Normalized counts | counts(dds, normalized = TRUE) |
| Transform for plots | vst(dds, blind = FALSE) |
| Transform blind to the design | vst(dds, blind = TRUE) |
| Regularized log | rlog(dds, blind = FALSE) |
| PCA | plotPCA(vsd, intgroup = "dex") |
| MA plot | plotMA(res) |
| Dispersion fit | plotDispEsts(dds) |
| One gene | plotCounts(dds, gene, intgroup, returnData = TRUE) |
| Column | Meaning |
|---|---|
baseMean |
Mean normalized count over all samples |
log2FoldChange |
Log2 fold change, numerator over reference |
lfcSE |
Standard error of the log2 fold change |
stat |
Wald statistic, absent after lfcShrink() |
pvalue |
Wald test p-value |
padj |
Benjamini-Hochberg adjusted p-value, NA when filtered |
Load the data
Section titled “Load the data”The count object comes from Michael Love’s airway 1.32.0 data package, which declares LGPL. It represents the Himes and colleagues experiment, deposited as GSE52778 and SRP033351. The source and license notice identifies the original object. This lesson derives its summaries and figures from that object.
library(DESeq2)library(airway)library(dplyr)library(tibble)library(ggplot2)library(ComplexHeatmap)
dir.create("outputs", showWarnings = FALSE)data(airway)dim(airway)colData(airway)[, c("cell", "dex")][1] 63677 8DataFrame with 8 rows and 2 columns cell dex <factor> <factor>SRR1039508 N61311 untrtSRR1039509 N61311 trtSRR1039512 N052611 untrtSRR1039513 N052611 trtSRR1039516 N080611 untrtSRR1039517 N080611 trtSRR1039520 N061011 untrtSRR1039521 N061011 trtBuild a DESeqDataSet
Section titled “Build a DESeqDataSet”airway is already a RangedSummarizedExperiment, so DESeqDataSet() wraps it and adds
the design.
The construction, prefilter, and PCA examples correspond to the DESeq2 vignette by Michael I. Love, Simon Anders, and Wolfgang Huber. The 1.30.1 source archive includes the total-count prefilter used below; later versions change that example. The package grants LGPL version 3 or later. The LGPL notice and GPL terms accompany this comparison.
dds <- DESeqDataSet(airway, design = ~ cell + dex)ddsclass: DESeqDataSetdim: 63677 8metadata(2): '' versionassays(1): countsrownames(63677): ENSG00000000003 ENSG00000000005 ... ENSG00000273492 ENSG00000273493rowData names(10): gene_id gene_name ... seq_coord_system symbolcolnames(8): SRR1039508 SRR1039509 ... SRR1039520 SRR1039521colData names(9): SampleName cell ... Sample BioSampleA plain count matrix and a sample sheet go through DESeqDataSetFromMatrix() instead.
The rows of the sample sheet must be in the same order as the matrix columns.
count_matrix <- assay(airway, "counts")sample_sheet <- as.data.frame(colData(airway))[, c("cell", "dex")]dds_from_matrix <- DESeqDataSetFromMatrix( countData = count_matrix, colData = sample_sheet, design = ~ cell + dex)all(colnames(count_matrix) == rownames(sample_sheet))[1] TRUESalmon or kallisto quantifications enter through the tximport package and
DESeqDataSetFromTximport(txi, colData = sample_sheet, design = ~ cell + dex), which
this image cannot run because it lacks tximport; the
STAR & Salmon guide covers the quantification step.
Prefilter low counts
Section titled “Prefilter low counts”A gene with fewer than 10 reads over all eight samples has no power to show a change. Dropping those genes removes 41,308 of the 63,677 rows and makes the fit faster.
keep <- rowSums(counts(dds)) >= 10dds <- dds[keep, ]c(before = length(keep), after = nrow(dds))before after 63677 22369Set the reference level
Section titled “Set the reference level”The dex factor in airway lists trt first. That makes the treated samples the
reference and flips the sign of every fold change, so relevel before DESeq().
levels(dds$dex)dds$dex <- relevel(dds$dex, ref = "untrt")levels(dds$dex)[1] "trt" "untrt"[1] "untrt" "trt"Run the model
Section titled “Run the model”DESeq() estimates size factors and dispersions, fits the model, and runs the Wald test.
resultsNames() lists the coefficients you can ask for by name.
dds <- DESeq(dds)resultsNames(dds)[1] "Intercept" "cell_N061011_vs_N052611"[3] "cell_N080611_vs_N052611" "cell_N61311_vs_N052611"[5] "dex_trt_vs_untrt"Extract results
Section titled “Extract results”With no arguments, results() returns the last coefficient of the design, here the
treatment effect. summary() counts genes at the default adjusted p-value of 0.1.
res <- results(dds)summary(res)out of 22369 with nonzero total read countadjusted p-value < 0.1LFC > 0 (up) : 2610, 12%LFC < 0 (down) : 2224, 9.9%outliers [1] : 0, 0%low counts [2] : 4337, 19%(mean count < 5)[1] see 'cooksCutoff' argument of ?results[2] see 'independentFiltering' argument of ?resultsAsk for a coefficient by name. alpha sets the FDR target that independent filtering
optimizes for, and the cutoff summary() reports.
res_name <- results(dds, name = "dex_trt_vs_untrt", alpha = 0.05)summary(res_name)out of 22369 with nonzero total read countadjusted p-value < 0.05LFC > 0 (up) : 2208, 9.9%LFC < 0 (down) : 1822, 8.1%outliers [1] : 0, 0%low counts [2] : 5204, 23%(mean count < 6)[1] see 'cooksCutoff' argument of ?results[2] see 'independentFiltering' argument of ?resultsA contrast is a factor, a numerator level and a denominator level. It reproduces a
coefficient, and it also reaches comparisons that are not one, such as two donors.
res_dex <- results(dds, contrast = c("dex", "trt", "untrt"))all.equal(res_dex$log2FoldChange, res$log2FoldChange)res_cell <- results(dds, contrast = c("cell", "N080611", "N61311"))mcols(res_cell)$description[2][1] TRUE[1] "log2 fold change (MLE): cell N080611 vs N61311"lfcThreshold tests whether the absolute log2 fold change exceeds a value. It calls 243
genes at an adjusted p-value of 0.05, where filtering the table on fold change after the
test keeps 823, as the count further down shows.
res_lfc1 <- results(dds, lfcThreshold = 1, alpha = 0.05)summary(res_lfc1)out of 22369 with nonzero total read countadjusted p-value < 0.05LFC > 1.00 (up) : 149, 0.67%LFC < -1.00 (down) : 94, 0.42%outliers [1] : 0, 0%low counts [2] : 3036, 14%(mean count < 3)[1] see 'cooksCutoff' argument of ?results[2] see 'independentFiltering' argument of ?resultsLikelihood ratio test
Section titled “Likelihood ratio test”test = "LRT" compares the full design with a reduced one and asks whether the
dropped terms explain any variance. Use it when a factor has three or more levels, or
for a time course, where one test should ask whether any level differs.
dds_lrt <- DESeq(dds, test = "LRT", reduced = ~ cell)res_lrt <- results(dds_lrt)mcols(res_lrt)$description[4]summary(res_lrt)[1] "LRT statistic: '~ cell + dex' vs '~ cell'"
out of 22369 with nonzero total read countadjusted p-value < 0.1LFC > 0 (up) : 2595, 12%LFC < 0 (down) : 2218, 9.9%outliers [1] : 0, 0%low counts [2] : 4337, 19%(mean count < 5)[1] see 'cooksCutoff' argument of ?results[2] see 'independentFiltering' argument of ?resultsWith only two levels of dex, the LRT and the Wald test agree closely, at 4,813 genes
against 4,834 at an adjusted p-value of 0.1. The p-values come from the LRT, but the
log2FoldChange column still holds the estimate of the last coefficient.
Shrink fold changes
Section titled “Shrink fold changes”lfcShrink() with type = "apeglm" pulls noisy fold changes of low count genes toward
zero and leaves well measured genes alone. Use the shrunken values to rank and plot genes.
res_shrunk <- lfcShrink(dds, coef = "dex_trt_vs_untrt", type = "apeglm")tibble( gene_id = rownames(res), base_mean = round(res$baseMean, 1), mle = round(res$log2FoldChange, 2), apeglm = round(res_shrunk$log2FoldChange, 2)) |> arrange(desc(abs(mle) - abs(apeglm))) |> head(5)# A tibble: 5 × 4 gene_id base_mean mle apeglm <chr> <dbl> <dbl> <dbl>1 ENSG00000265702 3.3 5.19 0.262 ENSG00000264569 2.8 4.81 0.183 ENSG00000222939 2.4 4.61 0.154 ENSG00000263567 4.1 -4.58 -0.215 ENSG00000171051 3.3 4.32 0.25The five genes above have a mean normalized count below five, and apeglm takes each
one from a fold change above 4 to one below 0.3. apeglm takes a coef, not a contrast. For a
comparison that is not a coefficient, relevel the factor so that it becomes one and run
DESeq() again. Older tutorials call lfcShrink(type = "normal") or fit with
DESeq(dds, betaPrior = TRUE). apeglm is now the default type, and the DESeq2
vignette recommends it over normal.
Results as a tibble
Section titled “Results as a tibble”The shrunken table keeps the p-values of the Wald test and drops the stat column.
Convert it to a tibble for dplyr.
res_tbl <- res_shrunk |> as.data.frame() |> rownames_to_column("gene_id") |> as_tibble() |> arrange(padj)print(res_tbl, n = 5)# A tibble: 22,369 × 6 gene_id baseMean log2FoldChange lfcSE pvalue padj <chr> <dbl> <dbl> <dbl> <dbl> <dbl>1 ENSG00000152583 997. 4.56 0.186 4.11e-136 7.41e-1322 ENSG00000165995 495. 3.28 0.133 4.46e-135 4.02e-1313 ENSG00000120129 3409. 2.94 0.123 3.03e-129 1.82e-1254 ENSG00000101347 12703. 3.75 0.158 7.68e-129 3.46e-1255 ENSG00000189221 2342. 3.34 0.143 5.21e-123 1.88e-119# ℹ 22,364 more rowsCount the genes past both cutoffs, split by direction.
res_tbl |> filter(padj < 0.05, abs(log2FoldChange) > 1) |> count(direction = if_else(log2FoldChange > 0, "up", "down"))# A tibble: 2 × 2 direction n <chr> <int>1 down 3692 up 454Normalized counts
Section titled “Normalized counts”Size factors scale each library to a common depth. counts(normalized = TRUE) divides
the raw counts by them.
round(sizeFactors(dds), 3)norm_counts <- counts(dds, normalized = TRUE)round(norm_counts[1:3, 1:4], 1)SRR1039508 SRR1039509 SRR1039512 SRR1039513 SRR1039516 SRR1039517 SRR1039520 1.024 0.896 1.180 0.670 1.178 1.399 0.921SRR1039521 0.945 SRR1039508 SRR1039509 SRR1039512 SRR1039513ENSG00000000003 663.3 499.9 740.1 608.9ENSG00000000419 456.2 574.7 526.5 544.8ENSG00000000457 254.0 235.5 223.0 244.8Variance stabilizing transformation
Section titled “Variance stabilizing transformation”vst() returns values on a log2 scale whose variance no longer grows with the mean,
the input for PCA, clustering and heatmaps. blind = FALSE lets the design inform the
dispersion trend; blind = TRUE is the choice for QC that must not see the groups.
vsd <- vst(dds, blind = FALSE)round(assay(vsd)[1:3, 1:4], 2) SRR1039508 SRR1039509 SRR1039512 SRR1039513ENSG00000000003 9.75 9.44 9.88 9.66ENSG00000000419 9.35 9.59 9.50 9.54ENSG00000000457 8.79 8.72 8.67 8.75rlog and the blind argument
Section titled “rlog and the blind argument”rlog() is the other variance stabilizing transformation. It fits a shrunken log2 value
for each gene and sample, which is slower but can work better than vst() on a small
study with library sizes that vary a lot. The DESeq2 vignette recommends vst() for
large studies. blind = TRUE ignores the design and suits QC that must not see the
groups. blind = FALSE uses the design for the dispersion trend only, so a strong
treatment effect does not inflate it.
rld <- rlog(dds, blind = FALSE)vsd_blind <- vst(dds, blind = TRUE)round(rbind( vst = assay(vsd)[1:3, 1], vst_blind = assay(vsd_blind)[1:3, 1], rlog = assay(rld)[1:3, 1]), 2) ENSG00000000003 ENSG00000000419 ENSG00000000457vst 9.75 9.35 8.79vst_blind 9.46 8.96 8.21rlog 9.39 8.87 7.96The three transformations put the same gene in the same sample as much as 0.83 apart, so compare samples within one transformation and never across two.
plotPCA(vsd, intgroup = "dex") returns a finished ggplot of the 500 most variable
genes. returnData = TRUE hands back the coordinates instead, with the percent of
variance in an attribute, so you can draw the plot yourself.
pca_df <- plotPCA(vsd, intgroup = c("dex", "cell"), returnData = TRUE)percent_var <- round(100 * attr(pca_df, "percentVar"))percent_var[1] 48 23pca_plot <- ggplot(pca_df, aes(PC1, PC2, color = dex, shape = cell)) + geom_point(size = 3) + scale_color_manual(values = c(untrt = "#4DBBD5", trt = "#E64B35")) + labs( x = paste0("PC1: ", percent_var[1], "% variance"), y = paste0("PC2: ", percent_var[2], "% variance") ) + theme_minimal(base_size = 12)ggsave("outputs/deseq2-pca.png", pca_plot, width = 6, height = 4.5, dpi = 150, bg = "white")
Treatment drives PC1 and the donor drives PC2, which is why the design carries cell.
MA plot
Section titled “MA plot”plotMA() draws base graphics, so open a file device around it. The two panels show
what shrinkage does.
png("outputs/deseq2-ma.png", width = 10, height = 4.5, units = "in", res = 150)par(mfrow = c(1, 2))plotMA(res, ylim = c(-5, 5), main = "results(): MLE")plotMA(res_shrunk, ylim = c(-5, 5), main = "lfcShrink(): apeglm")invisible(dev.off())
Dispersion plot
Section titled “Dispersion plot”Each gene gets a dispersion estimate, a trend is fitted across genes, and the final value is shrunk toward that trend.
png("outputs/deseq2-dispersion.png", width = 6, height = 5, units = "in", res = 150)plotDispEsts(dds)invisible(dev.off())
The black row at 1e-08 holds genes whose gene-wise estimate hit the lower bound. The fitted trend should run through the middle of the gene-wise cloud and fall as the mean rises, as it does here.
Counts for one gene
Section titled “Counts for one gene”plotCounts(returnData = TRUE) gives the normalized counts of one gene with the sample
columns attached.
top_gene <- res_tbl$gene_id[1]gene_counts <- plotCounts(dds, gene = top_gene, intgroup = c("dex", "cell"), returnData = TRUE)count_plot <- ggplot(gene_counts, aes(dex, count, group = cell)) + geom_line(color = "grey60") + geom_point(aes(color = dex), size = 3) + scale_color_manual(values = c(untrt = "#4DBBD5", trt = "#E64B35")) + scale_y_log10() + labs(title = top_gene, x = NULL, y = "Normalized count") + theme_minimal(base_size = 12) + theme(legend.position = "none")ggsave("outputs/deseq2-gene-counts.png", count_plot, width = 4, height = 4, dpi = 150, bg = "white")
Volcano plot
Section titled “Volcano plot”The volcano plot uses the shrunken fold changes, so low count genes no longer stretch the x axis.
volcano_df <- res_tbl |> filter(!is.na(padj)) |> mutate(direction = case_when( padj < 0.05 & log2FoldChange > 1 ~ "up", padj < 0.05 & log2FoldChange < -1 ~ "down", .default = "ns" ))volcano_plot <- ggplot(volcano_df, aes(log2FoldChange, -log10(padj), color = direction)) + geom_point(size = 0.8, alpha = 0.6) + scale_color_manual(values = c(down = "#4DBBD5", ns = "grey70", up = "#E64B35")) + geom_hline(yintercept = -log10(0.05), linetype = "dashed") + geom_vline(xintercept = c(-1, 1), linetype = "dashed") + labs(x = "log2 fold change, apeglm", y = "-log10 adjusted p-value") + theme_minimal(base_size = 12)ggsave("outputs/deseq2-volcano.png", volcano_plot, width = 6, height = 4.5, dpi = 150, bg = "white")
Sample distance heatmap
Section titled “Sample distance heatmap”Euclidean distances between samples on the VST values show which samples resemble each other before any test.
sample_dist <- as.matrix(dist(t(assay(vsd))))rownames(sample_dist) <- paste(vsd$dex, vsd$cell)colnames(sample_dist) <- rownames(sample_dist)dist_heatmap <- Heatmap( sample_dist, name = "distance", col = circlize::colorRamp2(c(0, max(sample_dist)), c("#3C5488", "white")))png("outputs/deseq2-sample-distance.png", width = 6, height = 5, units = "in", res = 150)draw(dist_heatmap)invisible(dev.off())
See also
Section titled “See also”- DESeq2 & pyDESeq2 fits this model in R and Python side by side, and shrinks the fold changes.
- Visualization labels the volcano plot with gene symbols and draws a heatmap of the top genes.
- Normalization explains size factors and the VST.
Scientific references
Section titled “Scientific references”Himes and colleagues, 2014 report the airway experiment used here.
Love, Huber, and Anders, 2014 describe the DESeq2 count model and its shrinkage of dispersion and fold change estimates.
Further reading
Section titled “Further reading”The DESeq2 vignette explains design coefficients, explicit contrasts, independent filtering, and fold change shrinkage. Read the transformation and PCA sections before comparing samples, because blind changes how the dispersion trend uses the design.
The airway construction vignette identifies the eight samples and explains how reads become the count object. The DESeq2 1.30.1 source vignette retains the total-count prefilter shown here; current tutorial filtering differs.