| name | bio-de-deseq2-basics |
| description | Perform differential expression analysis using DESeq2 in R/Bioconductor. Use for analyzing RNA-seq count data, creating DESeqDataSet objects, running the DESeq workflow, and extracting results with log fold change shrinkage. Use when performing DE analysis with DESeq2. |
| tool_type | r |
| primary_tool | DESeq2 |
Version Compatibility
Reference examples tested with: DESeq2 1.42+, Salmon 1.10+, edgeR 4.0+, scanpy 1.10+
Before using code patterns, verify installed versions match. If versions differ:
- R:
packageVersion('<pkg>') then ?function_name to verify parameters
If code throws ImportError, AttributeError, or TypeError, introspect the installed
package and adapt the example to match the actual API rather than retrying.
DESeq2 Basics
Differential expression analysis using DESeq2 for RNA-seq count data.
Required Libraries
library(DESeq2)
library(apeglm)
Installation
if (!require('BiocManager', quietly = TRUE))
install.packages('BiocManager')
BiocManager::install('DESeq2')
BiocManager::install('apeglm')
Creating DESeqDataSet
Goal: Construct a DESeqDataSet object from various input formats for DE analysis.
Approach: Wrap count data and sample metadata into the DESeq2 container, specifying the experimental design formula.
"Load my RNA-seq counts into DESeq2" → Create a DESeqDataSet from a count matrix, SummarizedExperiment, or tximport object with sample metadata and a design formula.
From Count Matrix
dds <- DESeqDataSetFromMatrix(countData = counts,
colData = coldata,
design = ~ condition)
From SummarizedExperiment
library(SummarizedExperiment)
dds <- DESeqDataSet(se, design = ~ condition)
From tximport (Salmon/Kallisto)
library(tximport)
txi <- tximport(files, type = 'salmon', tx2gene = tx2gene)
dds <- DESeqDataSetFromTximport(txi, colData = coldata, design = ~ condition)
Standard DESeq2 Workflow
Goal: Run the complete DESeq2 pipeline from raw counts to shrunken log fold change estimates.
Approach: Create dataset, pre-filter low-count genes, set reference level, run size factor estimation + dispersion estimation + Wald test, then apply LFC shrinkage.
"Find differentially expressed genes between treated and control" → Test for significant expression changes between conditions using negative binomial models with empirical Bayes shrinkage.
dds <- DESeqDataSetFromMatrix(countData = counts,
colData = coldata,
design = ~ condition)
keep <- rowSums(counts(dds)) >= 10
dds <- dds[keep,]
dds$condition <- relevel(dds$condition, ref = 'control')
dds <- DESeq(dds)
res <- results(dds)
resLFC <- lfcShrink(dds, coef = 'condition_treated_vs_control', type = 'apeglm')
Design Formulas
Goal: Specify the experimental design to model biological and nuisance variables.
Approach: Build R formula objects that encode condition, batch, and interaction terms for the GLM.
design = ~ condition
design = ~ batch + condition
design = ~ genotype + treatment + genotype:treatment
design = ~ genotype + treatment
Specifying Contrasts
Goal: Extract results for specific pairwise or complex comparisons from a fitted DESeq2 model.
Approach: Use coefficient names or contrast vectors to define which groups to compare.
resultsNames(dds)
res <- results(dds, name = 'condition_treated_vs_control')
res <- results(dds, contrast = c('condition', 'treated', 'control'))
res <- results(dds, contrast = list('conditionB', 'conditionA'))
Log Fold Change Shrinkage
Goal: Reduce noisy fold change estimates for low-count genes to improve ranking and visualization.
Approach: Apply empirical Bayes shrinkage (apeglm, ashr, or normal) to moderate log fold changes toward zero.
resLFC <- lfcShrink(dds, coef = 'condition_treated_vs_control', type = 'apeglm')
resLFC <- lfcShrink(dds, coef = 'condition_treated_vs_control', type = 'ashr')
resLFC <- lfcShrink(dds, coef = 'condition_treated_vs_control', type = 'normal')
Setting Significance Thresholds
Goal: Control the stringency of differential expression calls using adjusted p-value and fold change cutoffs.
Approach: Set alpha for multiple testing correction and optionally apply a minimum log fold change threshold.
res <- results(dds)
res <- results(dds, alpha = 0.05)
res <- results(dds, lfcThreshold = 1)
Accessing DESeq2 Results
Goal: Retrieve, filter, and sort DE results for downstream use.
Approach: Extract results as a data frame, subset by significance, and order by p-value or fold change.
summary(res)
sig <- subset(res, padj < 0.05)
resOrdered <- res[order(res$padj),]
resOrdered <- res[order(abs(res$log2FoldChange), decreasing = TRUE),]
res_df <- as.data.frame(res)
Result Columns
| Column | Description |
|---|
baseMean | Mean of normalized counts across all samples |
log2FoldChange | Log2 fold change (treatment vs control) |
lfcSE | Standard error of log2 fold change |
stat | Wald statistic |
pvalue | Raw p-value |
padj | Adjusted p-value (Benjamini-Hochberg) |
Normalization and Counts
Goal: Obtain normalized expression values suitable for visualization and cross-sample comparison.
Approach: Extract size-factor-normalized counts or apply variance-stabilizing / rlog transformations.
normalized_counts <- counts(dds, normalized = TRUE)
sizeFactors(dds)
vsd <- vst(dds, blind = FALSE)
rld <- rlog(dds, blind = FALSE)
Multi-Factor Designs
Goal: Account for batch or other nuisance variables while testing the effect of interest.
Approach: Include batch as a covariate in the design formula so DESeq2 adjusts for it during testing.
dds <- DESeqDataSetFromMatrix(countData = counts,
colData = coldata,
design = ~ batch + condition)
dds <- DESeq(dds)
res <- results(dds, name = 'condition_treated_vs_control')
Interaction Models
Goal: Identify genes whose response to treatment differs between genotypes (or other factor combinations).
Approach: Fit a model with interaction terms and test the interaction coefficient for significance.
dds <- DESeqDataSetFromMatrix(countData = counts,
colData = coldata,
design = ~ genotype + treatment + genotype:treatment)
dds <- DESeq(dds)
res_interaction <- results(dds, name = 'genotypeKO.treatmentdrug')
res_interaction <- results(dds, contrast = list(
c('genotypeKO.treatmentdrug'),
c()
))
Likelihood Ratio Test
Goal: Test whether a factor (e.g., condition) explains significant variance compared to a reduced model.
Approach: Compare full and reduced GLMs using a likelihood ratio test instead of Wald tests.
dds <- DESeq(dds, test = 'LRT', reduced = ~ batch)
res <- results(dds)
Pre-Filtering Strategies
Goal: Remove uninformative genes to reduce multiple testing burden and improve statistical power.
Approach: Apply count-based filters requiring minimum expression across a threshold number of samples.
keep <- rowSums(counts(dds)) >= 10
dds <- dds[keep,]
keep <- rowSums(counts(dds) >= 10) >= 3
dds <- dds[keep,]
keep <- rowMeans(counts(dds, normalized = TRUE)) >= 10
dds <- dds[keep,]
Working with Existing Objects
design(dds) <- ~ batch + condition
dds <- DESeq(dds)
dds_subset <- dds[, dds$group == 'A']
dds_genes <- dds[rownames(dds) %in% gene_list,]
Exporting Results
Goal: Save DE results and normalized counts to files for sharing or downstream tools.
Approach: Convert results to data frames and write as CSV files.
write.csv(as.data.frame(resOrdered), file = 'deseq2_results.csv')
write.csv(as.data.frame(normalized_counts), file = 'normalized_counts.csv')
Common Errors
| Error | Cause | Solution |
|---|
| "design matrix not full rank" | Confounded variables or missing levels | Check coldata for confounding |
| "counts matrix should be integers" | Non-integer counts (e.g., from tximport) | Use DESeqDataSetFromTximport() |
| "all samples have 0 counts" | Gene filtering issue | Check count matrix format |
| "factor levels not in colData" | Typo in design formula | Verify column names in coldata |
Deprecated Features
| Feature | Status | Alternative |
|---|
| No-replicate designs | Removed (v1.22) | Require biological replicates |
betaPrior = TRUE | Deprecated | Use lfcShrink() instead |
rlog() for large datasets | Not recommended | Use vst() for >100 samples |
Quick Reference: Workflow Steps
dds <- DESeqDataSetFromMatrix(counts, coldata, design = ~ condition)
keep <- rowSums(counts(dds)) >= 10
dds <- dds[keep,]
dds$condition <- relevel(dds$condition, ref = 'control')
dds <- DESeq(dds)
res <- lfcShrink(dds, coef = resultsNames(dds)[2], type = 'apeglm')
sig_genes <- subset(res, padj < 0.05 & abslog2FoldChange
Related Skills
- edger-basics - Alternative DE analysis with edgeR
- de-visualization - MA plots, volcano plots, heatmaps
- de-results - Extract and export significant genes