Transcriptomics / DE and enrichment

How to Do Differential Expression and Enrichment Analysis

Once you have a gene count table from RNA-seq, three questions often stop people: which differential analysis method to use, how to set the background genes for enrichment, and what to rank by for GSEA. This page uses the airway data from Bioconductor as an example, from counts through DESeq2 results and GO/KEGG enrichment to GSEA. Each step gives its purpose, along with measured numbers.

Short answer

Differential analysis of RNA-seq takes raw integer counts and sample groups, estimates fold changes and significance with DESeq2, and then selects differential genes by adjusted P value and fold change. Enrichment analysis has two kinds: over-representation analysis (ORA) tests which pathways the differential genes concentrate in, with the background set to the genes actually detected; GSEA uses the ranking of all genes to judge whether a pathway is overall up- or down-regulated. Without biological replicates, the significance cannot be trusted.

About this page

Tutorial
What this page solves
You have a gene count table from RNA-seq, with several treated and control samples. You want to know which genes changed and which pathways they relate to, but you are not sure whether to use DESeq2 or edgeR, or how to set the background for enrichment.
Who it is for
Graduate students and researchers who have aligned or quantified RNA-seq data and can use R, but have not run differential or enrichment analysis before.
What you will have
You will have a DESeq2 result table for all genes, a list of differential genes, GO and KEGG enrichment tables, GSEA results, and a volcano plot, a dot plot and a GSEA curve plot, and you will be able to justify each parameter.
Covers
  • Use DESeq2 to get differential genes from raw counts, with a paired factor and the direction of the comparison set.
  • GO and KEGG over-representation analysis with clusterProfiler, and ranking and interpretation for GSEA.
  • Choosing among DESeq2, edgeR and limma-voom, and what to do without biological replicates.
  • Common errors and reasons results differ (see the troubleshooting section).
Does not cover
  • Read alignment and quantification, meaning how to run featureCounts or Salmon.
  • Differential analysis of single-cell data; see the single-cell workflow guide.
  • Differential analysis of microarray data; see the GEO data-mining guide.
  • Functional validation experiments.

Main steps

Step 1 · Prepare the data

Why this stepDESeq2 needs raw integer counts and sample groups. This step loads the data, sets the control group as the reference level, and puts the paired cell line into the model.

This example uses the airway data from Bioconductor: four cell lines, each with treated (dex) and untreated (untrt) samples. The cell line is a paired factor and must be in the model; otherwise differences between cell lines are counted as residual noise.

relevel sets untrt as the reference level, so the results describe trt relative to untrt. Pre-filtering removes low-count genes only to save computation: 63,677 genes are reduced to 16,139, and DESeq() takes 3.7 seconds instead of 11.8, with almost the same number of differential genes.

If your input comes from featureCounts or Salmon, see the choice “featureCounts or Salmon input” for how to import it.

Full airway workflow (run on this page)r
library(DESeq2); library(airway)
data(airway)
airway$dex <- relevel(airway$dex, ref = "untrt")
dds <- DESeqDataSet(airway, design = ~ cell + dex)   # cell: the paired cell line, placed first

## Pre-filter: count >= 10 in at least smallestGroupSize samples (as in the official vignette)
smallestGroupSize <- 4
keep <- rowSums(counts(dds) >= 10) >= smallestGroupSize
dds  <- dds[keep, ]                                    # 63,677 -> 16,139

Step 2 · Run

Why this stepDESeq2 estimates the dispersion and fold change of each gene, then tests whether the two groups differ. results() turns the output into a table, and contrast names the two groups being compared.

DESeq() took 3.7 seconds in this example. resultsNames() lists the available coefficient names. alpha should match the padj threshold you finally use (0.05 in this example).

Full airway workflow (run on this page)r
dds <- DESeq(dds)                                      # measured on this page: 3.7 s
resultsNames(dds)                                      # list the available coef names
res <- results(dds, contrast = c("dex", "trt", "untrt"), alpha = 0.05)
summary(res)

Step 3 · Filter

Why this steppadj and |log2FC| decide which genes are selected, and the selected list is the input for enrichment. Save the results for all genes separately, because GSEA and the background both need them.

In this example, the unshrunk results with padj < 0.05 and |log2FC| > 1 give 951 differential genes (490 up, 461 down). Shrunken log2FC is used for ranking and plotting; see the choice “When to shrink log2FC”.

For the meaning of the thresholds and the difference between padj and pvalue, see the explanation section; for measured gene counts under common thresholds, see the choices section.

Full airway workflow (run on this page)r
## Shrink LFC: apeglm accepts coef only
resLFC <- lfcShrink(dds, coef = "dex_trt_vs_untrt", type = "apeglm")

deg <- subset(as.data.frame(res), padj < 0.05 & abs(log2FoldChange) > 1)
nrow(deg)                                               # 951 (490 up, 461 down)
write.csv(as.data.frame(res), "deseq2_all_genes.csv")  # keep all genes; GSEA and the universe need them

Step 4 · Enrichment

Why this stepORA tests whether a pathway contains more differential genes than chance would predict. The gene pool that chance is drawn from is set by the background (universe), so the universe must be the genes actually detected.

The code first converts ENSEMBL IDs to Entrez IDs, because KEGG and most GO analyses use Entrez IDs. After conversion, 888 differential genes are used for enrichment, with 13,776 detected genes as the background.

enrichGO gives 543 significant terms, which simplify reduces to 202 by merging similar terms. enrichKEGG gives 17 significant pathways. For the effect of the universe, see the explanation section; for handling genes lost in ID conversion, see the choices section.

ID conversion, enrichGO and enrichKEGG (run on this page)r
library(clusterProfiler); library(org.Hs.eg.db)

## 1. ID conversion: ENSEMBL -> ENTREZID; report the loss rate
eg <- mapIds(org.Hs.eg.db, keys = rownames(res), keytype = "ENSEMBL",
             column = "ENTREZID", multiVals = "first")
mean(is.na(eg))                                  # airway: 13.5% have no Entrez ID

sig    <- rownames(res)[which(res$padj < 0.05 & abs(res$log2FoldChange) > 1)]
tested <- rownames(res)[!is.na(res$padj)]       # genes that were actually tested
sigE <- unique(na.omit(eg[sig]))                 # 888
uniE <- unique(na.omit(eg[tested]))              # 13,776, used as the background

## 2. GO
ego <- enrichGO(sigE, OrgDb = org.Hs.eg.db, ont = "BP", universe = uniE,
                pvalueCutoff = 0.05, qvalueCutoff = 0.2, readable = TRUE)
ego2 <- simplify(ego, cutoff = 0.7)              # remove redundancy: 543 -> 202 terms

## 3. KEGG (reads rest.kegg.jp online)
ekk <- enrichKEGG(sigE, organism = "hsa", universe = uniE, pvalueCutoff = 0.05)
ekk <- setReadable(ekk, OrgDb = org.Hs.eg.db, keyType = "ENTREZID")
saveRDS(ekk, "enrichKEGG_result.rds")            # save the object; KEGG updates weekly
readLines("https://rest.kegg.jp/info/kegg")[2]   # record the KEGG data release for the methods section

Step 5 · GSEA

Why this stepGSEA does not filter genes. It ranks all tested genes by a statistic and checks whether the members of a gene set cluster at the top or the bottom. This shows whether a pathway is overall up- or down-regulated.

The ranking uses the Wald statistic from DESeq2 (the stat column), which combines effect size and reliability and carries a sign. The gene sets are the MSigDB hallmark collection, obtained with msigdbr.

seed = TRUE fixes the random seed so that results can be reproduced. For a comparison of ranking metrics, see the choices section; for how to read NES and FDR, see the explanation section.

GSEA and gseGO (run on this page)r
library(clusterProfiler); library(msigdbr)

## Ranked vector: all tested genes, sorted by Wald stat in decreasing order, named by Entrez ID
rk <- res$stat; names(rk) <- eg[rownames(res)]
rk <- rk[!is.na(rk) & !is.na(names(rk))]
rk <- sort(rk[!duplicated(names(rk))], decreasing = TRUE)   # 13,952 genes

## MSigDB hallmark (since msigdbr 10 the argument is collection and the column is ncbi_gene)
h  <- msigdbr(species = "Homo sapiens", collection = "H")
t2g <- data.frame(term = h$gs_name, gene = as.character(h$ncbi_gene))

gs <- GSEA(rk, TERM2GENE = t2g, minGSSize = 15, maxGSSize = 500,
           pvalueCutoff = 0.05, eps = 0, seed = TRUE)      # seed = TRUE makes results reproducible
gg <- gseGO(rk, OrgDb = org.Hs.eg.db, ont = "BP", minGSSize = 15, maxGSSize = 500,
            pvalueCutoff = 0.05, eps = 0, seed = TRUE)      # 11.8 s on this page, 198 terms
## Do not pass nPerm = 1000: current versions use fgsea multilevel sampling and warn against nPerm

Step 6 · Plots

Why this stepThe plots check that the results match the thresholds used earlier. The volcano plot’s y axis, threshold lines and colours must match the filter.

The volcano plot’s y axis is -log10(padj), with threshold lines at padj 0.05 and |log2FC| 1, as in step 3. The 15 genes with the smallest padj are labelled.

dotplot shows the GO results after redundancy removal, and gseaplot2 draws the GSEA curve. For plotting details, see the reference section; for common plotting mistakes, see the troubleshooting section.

Code for the three plots (runs as tested on this page)r
library(ggplot2); library(ggrepel); library(enrichplot)

## Volcano plot: padj on the y axis; threshold lines match the filter
df <- as.data.frame(res)
df$symbol <- mapIds(org.Hs.eg.db, rownames(df), keytype = "ENSEMBL", column = "SYMBOL")
df <- df[!is.na(df$padj), ]
df$grp <- with(df, ifelse(padj < 0.05 & log2FoldChange >  1, "up",
                    ifelse(padj < 0.05 & log2FoldChange < -1, "down", "ns")))
lab <- head(df[df$grp != "ns", ][order(df$padj[df$grp != "ns"]), ], 15)
ggplot(df, aes(log2FoldChange, -log10(padj), colour = grp)) +
  geom_point(size = 0.6, alpha = 0.6) +
  scale_colour_manual(values = c(up = "#c0392b", down = "#2471a3", ns = "grey70")) +
  geom_vline(xintercept = c(-1, 1), linetype = 2) +
  geom_hline(yintercept = -log10(0.05), linetype = 2) +
  geom_text_repel(data = lab, aes(label = symbol), colour = "black", size = 3) +
  theme_bw()

## Dot plot: GO terms after simplify
dotplot(ego2, showCategory = 15)

## GSEA plot: pvalue_table needs gridExtra; use a width of at least 10 inches so the table is not clipped
p <- gseaplot2(gs, geneSetID = 1:2, pvalue_table = TRUE)
ggsave("gsea.png", p, width = 10, height = 6, dpi = 300)

Choose by your situation

Hand it to an agent

You can describe the full differential expression and enrichment task in one instruction.

Example instruction: “Run DESeq2 on counts.txt from featureCounts and samples.csv with design ~ batch + condition, comparing trt to ctrl; cutoffs padj < 0.05 and |log2FC| > 1; draw a volcano plot with apeglm-shrunken LFC; run GO BP and KEGG enrichment with detected genes as the background, using local KEGG data and recording its release; run GSEA on hallmark and GO BP ranked by the Wald stat with a fixed seed; output the DE table, enrichment tables and three plots.”

The agent installs R and the Bioconductor packages in an isolated cloud computer and follows this page: it checks that the sample table matches the count columns, pre-filters, runs DESeq2 and lfcShrink, converts IDs and reports the loss rate, runs ORA with a universe, GSEA and the plots. The project keeps the scripts, sessionInfo, KEGG data date, result tables and figures, so the analysis can be reproduced. The agent reviews its results adversarially, for example checking that volcano thresholds match the filter, that a universe was set and that GSEA used a fixed seed.

You still need to check that group and batch labels match your lab records, that the design reflects the real pairing structure, that the cutoffs follow conventions in your field, and that the enriched pathways make biological sense.

Choices

For a routine two-group comparison the three give highly overlapping results; a wrong choice matters mainly at extreme sample sizes or with unusual data types.

Measured on this page (R 4.5.3, DESeq2 1.50.2, edgeR 4.10.5, limma 3.68.5, clusterProfiler 4.18.4, Apple M2 8-core, 16 GB): DESeq2 gives 951 differential genes, edgeR QL 1183, and limma-voom 1145; the intersection of the three is 910 and the union 1227. The differences lie mainly in borderline genes with effect sizes close to 1. In a paper, state the method and version you used; there is no need to take the intersection of the three.

Equivalent edgeR QL and limma-voom code (airway)r
library(edgeR); library(limma)
design <- model.matrix(~ cell + dex, data = as.data.frame(colData(airway)))
y <- DGEList(assay(airway)); keep <- filterByExpr(y, design)
y <- normLibSizes(y[keep, , keep.lib.sizes = FALSE])

## edgeR 4 quasi-likelihood pipeline (recommended in the user's guide)
fit <- glmQLFit(estimateDisp(y, design), design)
tt  <- topTags(glmQLFTest(fit, coef = "dextrt"), n = Inf)$table

## limma-voom
v  <- voom(y, design)
tl <- topTable(eBayes(lmFit(v, design)), coef = "dextrt", n = Inf)
SituationRecommendedBasis and cost of a wrong choice
RNA-seq counts, 3–6 biological replicates per groupDESeq2 or edgeR (QL pipeline)Both shrink dispersions across genes, which is more stable at small n; on this page the intersection of the three methods is 74% of their union
2 replicates per groupDESeq2 or edgeR, with conclusions treated as exploratoryIt runs, but Cook's distance outlier detection needs at least 3 replicates per group, so an outlier sample cannot be flagged
No biological replicatesDescriptive analysis only; edgeR with a fixed BCV for a candidate listDESeq2 exits with an error; edgeR results change 100-fold with the BCV value (next section)
Many samples (20+ per group), multiple factors or continuous covariateslimma-voomFast linear-model fitting; duplicateCorrelation handles repeated measures
Population cohorts, dozens to hundreds per groupWilcoxon rank-sum test, or DESeq2/edgeR with SVA/RUV for technical variationLi et al. (2022) ran permutation tests on 13 population datasets; at a 5% target FDR, the actual FDR of DESeq2/edgeR sometimes exceeded 20%
Microarray expression matrixlimmaThe data are continuous log-scale values and cannot go into DESeq2/edgeR
TPM, FPKM or other normalized matricesRecover raw counts; if only TPM exists, use limma-trend and say so in the methodsDESeq2/edgeR need integer counts; rounding FPKM distorts dispersion estimates
Measured on this page: airway (4 cell lines × treated/untreated), padj/FDR < 0.05 and |log2FC| > 1

Choices

The input must be raw integer counts. Read a featureCounts matrix directly; summarise Salmon transcript quantification to gene level with tximport before input. Do not sum TPM values yourself.

Import featureCounts or Salmon outputr
library(DESeq2)

## Option 1: featureCounts output (counts.txt; the first 6 columns are annotation)
fc  <- read.delim("counts.txt", comment.char = "#", check.names = FALSE)
cts <- as.matrix(fc[, 7:ncol(fc)])
rownames(cts) <- sub("\\.\\d+$", "", fc$Geneid)        # strip the version suffix from ENSG00000000003.15
colnames(cts) <- sub("\\.bam$", "", basename(colnames(cts)))

coldata <- read.csv("samples.csv", row.names = 1)    # row names = sample names; columns: condition, batch, ...
coldata$condition <- factor(coldata$condition, levels = c("ctrl", "trt"))  # the first level is the control
coldata$batch     <- factor(coldata$batch)
stopifnot(identical(rownames(coldata), colnames(cts))) # a mismatched order gives wrong results without any error
dds <- DESeqDataSetFromMatrix(cts, coldata, design = ~ batch + condition)

## Option 2: Salmon + tximport (gene level; passes estimated counts and a transcript-length offset)
library(tximport)
files <- file.path("salmon", rownames(coldata), "quant.sf"); names(files) <- rownames(coldata)
tx2gene <- read.csv("tx2gene.csv")                    # two columns: TXNAME, GENEID; same annotation release as the index
txi <- tximport(files, type = "salmon", tx2gene = tx2gene, ignoreTxVersion = TRUE)
dds <- DESeqDataSetFromTximport(txi, coldata, design = ~ batch + condition)

Choices

Without replicates, the biological variation within a group cannot be estimated, and any p value the software gives depends on an assumed value.

With no replicates, edgeR’s estimateDisp() returns NA for the dispersion. The edgeR manual suggests setting a BCV (the square root of the dispersion) by hand: 0.4 for well-controlled human samples, 0.1 for inbred model organisms, and 0.01 for technical replicates. On the same pair of samples, this page measured 1645, 346 and 17 genes with FDR < 0.05 at BCV 0.1, 0.2 and 0.4. The number of differential genes is set entirely by this assumed value, so the result can only be a candidate list.

What you can do without replicates: rank candidate genes by log2FC, draw an MA plot, run GSEA on the ranked list as a lead, and verify with qPCR or new replicates. What you cannot do: report padj, claim a gene is significantly different, or treat the list as confirmed for later ORA or network analysis.

edgeR with a fixed BCV (for a candidate list only)r
library(edgeR)
y <- DGEList(counts = cts[, c("ctrl_1", "trt_1")], group = c("ctrl", "trt"))
y <- normLibSizes(y)
bcv <- 0.4                                  # edgeR guide: 0.4 for human data, 0.1 for inbred model organisms, 0.01 for technical replicates
et  <- exactTest(y, dispersion = bcv^2)
topTags(et, n = 50)                         # a candidate list only; validate with qPCR or follow-up experiments

Choices

A wrong design is the most common reason results cannot be trusted, and it produces no error message.

Measured on this page: the four cell lines in airway each have treated and untreated samples. With design ~ cell + dex there are 4081 genes with padj < 0.05, and with ~ dex alone there are 2773, a 32% drop (with |log2FC| > 1 the counts are 951 and 785).

Batch is handled correctly by putting it in the design. Do not rewrite the counts with ComBat or removeBatchEffect before DESeq2; the output of removeBatchEffect is only for PCA and heatmap display. If the batch is unknown, estimate surrogate variables with sva and add them to the design as covariates.

Common contrast and shrinkage patternsr
## Two groups: numerator is treatment, denominator is control
results(dds, contrast = c("condition", "trt", "ctrl"))

## Three or more groups: any pairwise comparison
results(dds, contrast = c("condition", "drugB", "drugA"))

## For designs with interactions, combine factors into one group factor instead of reading interaction terms
dds$group <- factor(paste0(dds$genotype, "_", dds$condition))
design(dds) <- ~ batch + group
dds <- DESeq(dds)
results(dds, contrast = c("group", "KO_trt", "KO_ctrl"))

## When the comparison you want to shrink with apeglm is not an existing coef: relevel and refit
dds$condition <- relevel(dds$condition, ref = "drugA")
dds <- nbinomWaldTest(dds)                         # dispersions do not need to be re-estimated
lfcShrink(dds, coef = "condition_drugB_vs_drugA", type = "apeglm")
## Or use ashr, which supports contrast
lfcShrink(dds, contrast = c("condition", "drugB", "drugA"), type = "ashr")
ScenariodesignNotes
Two groups, no batch~ conditionThe first level of condition is the reference; set it with relevel() or factor(levels =)
Batch or pairing (same patient or cell line before/after)~ batch + conditionPut the variable of interest last; batch must be a factor, as a number it is treated as continuous
Multiple groups~ batch + conditionUse contrast = c("condition", "B", "A") for any pair; the result is B relative to A
Two factors with an interaction of interest~ batch + group (group combines the two factors)The officially recommended approach; avoids interpreting interaction coefficients directly
Batch fully confounded with group (one group per batch)Cannot be correctedThe model matrix is not full rank and DESeq2 errors; this is a design problem that analysis cannot fix

Choices

The threshold sets the number of differential genes and therefore the ORA result, so the methods must state it.

FilterGenes in airwayNote
padj < 0.1 (results default alpha)4889DESeq2's default; most papers do not use it
padj < 0.054081Controls FDR only, ignores effect size
padj < 0.05 and |log2FC| > 0.585 (1.5-fold)2025Common for small effects with many samples
padj < 0.05 and |log2FC| > 1 (2-fold)951The most common combination
padj < 0.05 after results(lfcThreshold = 1)241Tests whether |log2FC| is significantly above 1; stricter
pvalue < 0.05 (no multiple-testing correction)548834% more than padj < 0.05

Choices

lfcShrink changes only the log2FoldChange column; pvalue and padj stay the same.

Use shrunken values when presenting effect sizes

The raw log2FC of low-expression genes is very noisy, and shrinkage brings it closer to a credible value. Volcano plots, MA plots, candidate tables sorted by LFC, and GSEA ranked by LFC should all use the shrunken LFC.

Shrinkage reduces the number of differential genes

Measured here, genes with |log2FC| > 1 drop from 1091 to 769. Filtering with the shrunken LFC plus padj < 0.05 gives 749, fewer than the 951 from the raw LFC. State in the paper whether the log2FC was shrunk.

type = "normal" is not recommended for large LFC

In the comparison table of the DESeq2 vignette, normal does not keep the magnitude of large LFCs and cannot shrink interaction terms; apeglm has been the recommended default since 1.28. Measured here: apeglm 3.6 s, ashr 1.4 s.

Choices

clusterProfiler’s KEGG and most GO analyses use Entrez IDs, so ENSEMBL or SYMBOL IDs must be converted first.

Measured on this page: of 16,139 Ensembl genes converted to ENTREZID with bitr, 13.5% have no matching ID, and 180 Ensembl IDs match several Entrez IDs. Of the 951 differential genes, 63 are lost; by airway’s gene_biotype these are mainly lincRNA (23), pseudogene (15) and antisense (13), and only 5 protein-coding genes are lost. Most lost genes had no GO or KEGG annotation to begin with, so the effect on enrichment is small, but state the loss rate in the methods.

When bitr finds a one-to-many match, it returns several rows, and using them directly in ORA counts genes twice. Use mapIds(multiVals = "first") to keep one ID per gene, then apply unique().

  • SYMBOLs change when HGNC renames genes, so when merging data from different years, prefer Ensembl or Entrez IDs.
  • For mouse data use org.Mm.eg.db and set organism to "mmu" in enrichKEGG. A mismatch between species and annotation package causes “No gene can be mapped”; see the troubleshooting section.

Choices

enrichKEGG downloads KEGG data live in each new R session, so the analysis hangs whenever the network is unavailable.

In clusterProfiler 4.18, enrichKEGG defaults to use_internal_data = FALSE and reads two addresses: https://rest.kegg.jp/link/hsa/pathway and https://rest.kegg.jp/list/pathway/hsa. Measured here: the first call takes 9–10 s, and a second call in the same session takes about 2–3 s from memory; after restarting R it downloads again.

KEGG data is updated every week; when this page was checked, rest.kegg.jp/info/kegg showed version 2026/10/09. Rerunning the same script six months later may change the pathway gene counts and the significant pathways. Save the enrichKEGG result object, and state the KEGG data date in the methods.

When the network is unstable, or when results must be reproducible, use createKEGGdb to build a local KEGG.db package from the current KEGG data. Measured here: createKEGGdb 0.0.5 takes 7–9 s to build the human data, and the package is about 300 KB. With use_internal_data = TRUE the results match the online results exactly (the same 17 significant pathways), with a complete Description column. The KEGG.db package of the same name on Bioconductor has not been updated since 2012 and has been deprecated since Bioconductor 3.12, so do not download it from an old repository.

Build local KEGG data with createKEGGdb (run on this page)r
## Once: build and install a local package of current KEGG data (needs access to GitHub and rest.kegg.jp)
remotes::install_github("YuLab-SMU/createKEGGdb")
createKEGGdb::create_kegg_db("hsa")            # 7–9 s on this page; produces KEGG.db_1.0.tar.gz (about 300 KB)
install.packages("KEGG.db_1.0.tar.gz", repos = NULL, type = "source")

## Offline use afterwards
library(KEGG.db)
ekk_local <- enrichKEGG(sigE, organism = "hsa", universe = uniE, use_internal_data = TRUE)
head(ekk_local$Description)                     # plots need pathway names

Choices

GSEA takes a ranking of all tested genes and does not select differential genes. The choice of ranking metric affects the result more than any other parameter.

Ranking metricSignificant hallmark sets (p.adjust < 0.05)Properties
DESeq2 stat (Wald statistic)15 (11 up, 4 down)Reflects both effect size and confidence, signed, unaffected by independent filtering; recommended default
log2FC after lfcShrink (apeglm)3Reflects effect size only; unshrunken LFC pushes noisy low-count genes to the ends, do not use it
sign(log2FC) × -log10(pvalue)1Highly significant genes reach values above 100, so a few genes dominate the score; p values of 0 give Inf
Ranking DE genes onlygseGO drops to 2 terms (198 with all genes)Breaks the premise of GSEA; there is no background
Measured on this page: airway, 13,952 genes, MSigDB 2026.1 hallmark (50 sets), clusterProfiler GSEA, seed = TRUE

Concepts and judgment

Explanation

The thresholds decide which genes are selected. Understanding them lets you describe the methods clearly.

padj is the Benjamini-Hochberg adjusted value. padj < 0.05 means that among the genes called significant, the expected proportion of false discoveries is about 5%. It controls an expected proportion, and does not guarantee that every analysis stays below 5%.

The problem with using only pvalue < 0.05: this page tested about 15,800 genes, and even with no true differences, about 790 genes would be expected to have pvalue < 0.05. Reviewers who see unadjusted p values often ask for the analysis to be redone. If the pvalue filter gives too few genes, switch to padj < 0.1 or loosen |log2FC|, and state this honestly.

“padj < 0.05 plus |log2FC| > 1” and “lfcThreshold = 1” are two different things. The first tests whether log2FC differs from 0 and then filters on the point estimate; a gene whose point estimate just passes 1 may have a true effect below 1. To claim that expression changes by more than 2-fold, test with lfcThreshold.

Explanation

The universe sets the gene pool used for the chance comparison. If it is not set, genes that are not expressed in the tissue are also counted in the background.

Without a universe, the background is every annotated human gene in the database. Genes not expressed in the tissue can never be differential, yet they enter the background, so pathways highly expressed in the tissue are systematically called enriched. airway is smooth muscle cells of the airway; without a universe the extra pathways are common ones related to smooth muscle and signal transduction. Use the genes with non-NA padj as the universe, that is, the genes that actually took part in the test.

AnalysisUniverse = detected genesNo universe (whole genome)Measured note
enrichKEGG17 significant45 significantThe extra 32 include MAPK, Wnt, Hippo and FoxO pathways
enrichGO BP543 significant555 significant426 terms overlap; each has 100+ unique terms and the top terms differ
enrichKEGG + enrichment_force_universe = TRUE174 significant—Counts unannotated genes in the background and inflates significance; do not use
Measured on this page: 888 DE genes (Entrez), background of 13,776 detected genes, p.adjust < 0.05

Explanation

NES gives the direction, FDR gives the significance, and the leading edge is the set of genes that drive the enrichment.

Thresholds for NES and FDR

For R package results, read p.adjust (BH-adjusted) or qvalue, usually < 0.05. The FDR q-value in the Broad GSEA software is a different permutation-based estimate, and the official 25% cutoff is meant for generating hypotheses; if you write “FDR < 0.25” with the R package, state where it comes from. The sign of NES shows whether the gene set clusters at the top or bottom of the ranked list. |NES| is only for comparison and has no general significance cutoff; the claim that |NES| > 1 is significant has no statistical basis.

What the leading edge means

The leading edge is the members of the gene set that appear before the enrichment score peaks; they are the core genes that drive the signal. In clusterProfiler the gene list is in the core_enrichment column; in leading_edge, tags is the fraction of the gene set in the core, list is the peak position in the ranked list, and signal combines the two. For ADIPOGENESIS on this page, 62 of 189 genes are in the leading edge (tags = 33%). Choose genes for validation from core_enrichment.

How to read the GSEA curve

The peak in the upper panel is the enrichment score. A peak on the left with a positive value means the gene set is up-regulated in the treated group; the direction of the ranking is set by your contrast. The vertical bars mark where the gene set members fall in the ranking, and the members before the peak form the leading edge.

Reference and appendix

Reference

DESeq2 sets padj to NA on purpose, so know which category a row belongs to before you delete it.

After pre-filtering, independent filtering removes only 313 more genes. Outlier detection with Cook’s distance requires at least 3 replicates per group; with 2 replicates per group this mechanism does not work.

When you need unfiltered results, for example to keep all genes for GSEA, use results(dds, independentFiltering = FALSE). The GSEA ranking uses the stat column, which is not affected by independent filtering, so genes removed by independent filtering still have a stat value.

ReasonSymptomairway, no pre-filterWhat to do
All samples have zero countsbaseMean = 0; log2FC, pvalue and padj are all NA30,208 of 63,677 rowsNormal; pre-filtering removes them
An extreme outlier flagged by Cook's distancepvalue and padj are NA, baseMean is not 00Check for a bad sample; with ≥ 7 replicates per group DESeq2 replaces outliers and refits automatically
Removed by independent filtering (low mean count)pvalue present, padj NA16,687 (threshold baseMean 7.16)These genes have too little power; filtering them raises detections among the rest

Reference

The two share the same core algorithm, so differences almost always come from inputs and default parameters. Align them item by item to reproduce the result.

Some online answers say fgsea cannot compute a weighted statistic. This is outdated: the default gseaParam in fgsea and exponent in clusterProfiler are both 1, which matches the weighted score in Broad’s GSEA.

Source of differenceGSEA desktop (Broad)clusterProfiler / fgseaHow to align
Input and rankingStandard GSEA takes an expression matrix and ranks by Signal2Noise or similarTakes the ranked vector you provide (such as the Wald stat)Use GSEAPreranked in the desktop app with the same .rnk file
PermutationStandard GSEA permutes phenotype labels by default, with gene_set advised for small samples; Preranked only does gene_setPermutes genes only (fgsea multilevel sampling)Compare using Preranked on both sides
Gene set sizemin 15, max 500clusterProfiler minGSSize defaults to 10; standalone fgsea minSize defaults to 1Set minGSSize = 15, maxGSSize = 500 explicitly in R
Gene IDsPreranked defaults to Remap_Only, remapping symbols via chip annotationNo remapping; names must match the gene setsUse SYMBOL or Entrez consistently and remove duplicates
TiesRequires no duplicate ranking values; ties are ordered arbitrarilyWarns about ties and orders them arbitrarilyResolve ties before ranking, or accept small differences
Random seedDefaults to a timestamp, different every runDifferent every run without a seedFix the seed on both sides
Significance measureFDR q-value (from the permuted NES distribution)BH-adjusted p.adjustCompare NES direction and rank, not FDR values
Gene set releaseThe downloaded gmt fileCurrent msigdbr releaseUse the same gmt release

Reference

The thresholds, y axis and colours in a plot must match the filter used in the text.

Volcano plot

The y axis is -log10(padj), and the threshold lines match the text (padj 0.05 and |log2FC| 1 on this page). Remove genes with NA padj first, or ggplot gives a missing-value warning and drops points. Very significant genes can underflow to padj = 0, which becomes Inf after -log10; replace 0 with the smallest non-zero value and say so in the legend. Label genes chosen by padj or by a list you specify in advance.

Dot plot

By default, dotplot puts GeneRatio on the x axis, point size is the gene count and colour is p.adjust. The GeneRatio denominator is the number of annotated differential genes, not all differential genes. Show the redundancy-reduced terms, so the top 15 are not all levels of the same process.

Reference

State the items below in the paper and supplementary material; reviewers ask about them most often.

  • The size and source of the background gene set (universe), and how it relates to the BgRatio denominator.
  • Database versions: the KEGG data date, and the MSigDB and msigdbr versions.
  • The correction method (BH) and thresholds, and whether shrunken log2FC was used.
  • The random seed and the GSEA ranking metric.
  • Threshold lines and the y axis in the dot and volcano plots match the text, and the labelled genes are explained.

Chinese community

These come from author-tested posts on CSDN and Jianshu and were checked against clusterProfiler 4.18.4 and createKEGGdb 0.0.5.

Local KEGG data

CSDN authors hutong_oncology and qq_41547057 both hit online enrichKEGG failures or a sudden “No gene can be mapped” in 2023 and fixed it by building a local KEGG.db with createKEGGdb::create_kegg_db. The first also notes that a local database prevents online KEGG updates from changing results between runs. The workflow still works with current versions on this page and matches the online results.

Old KEGG.db builds missing Description break plots

hutong_oncology reports that some generated KEGG.db packages lacked pathway descriptions: the enrichment table was produced, but barplot and dotplot failed with “Error in ans[ypos] <- rep(yes, length.out = len)[ypos]” and “'x' is NULL so the result will be NULL”. Many posts blame a strict cutoff; the actual cause is the missing Description. The package built by createKEGGdb 0.0.5 here has complete descriptions; if you see this error, check head(ekk$Description) first.

The R.utils::setOption download trick no longer works

Older posts fix KEGG download failures with R.utils::setOption("clusterProfiler.download.method", "auto"). In clusterProfiler 4.18.4, KEGG downloads go through yulab.utils::yread, which calls readLines, and the source no longer reads this option. Fix network problems with a system proxy or a local KEGG.db.

“padj < 0.05 guarantees at most 5% false positives” is inaccurate

Jianshu and similar tutorials often explain padj this way. BH correction controls the expected proportion of false discoveries; in a single analysis the actual proportion can exceed 5%. Write “FDR controlled at 5%” in the methods, not “guaranteed”.

Troubleshooting

Find your error message or symptom below. Entries follow the order of the steps and roughly how often each problem comes up. Each entry gives the cause and the fix.

Error: The design matrix has the same number of samples and coefficients to fit, so estimation of dispersion is not possible

Cause: There are no biological replicates, so the number of samples equals the number of coefficients to estimate. DESeq2 has not supported designs without replicates since 1.22, so the older tutorial advice that DESeq2 works without replicates no longer applies.

Fix: Add biological replicates. If there are none, see the choice “What you can do without biological replicates”.

Results are shifted across samples, with no error message

Cause: If the row order of coldata does not match the column order of the counts, DESeq2 gives no error and the results are shifted.

Fix: Check the order before building the object.

stopifnot(identical(rownames(coldata), colnames(cts)))
bitr or mapIds fails to match almost every gene

Cause: featureCounts Geneid values carry a version number, for example ENSG00000000003.15, which does not match the IDs in the annotation database.

Fix: Remove the version number before conversion.

rownames(cts) <- sub("\\.\\d+$", "", fc$Geneid)
tximport returns the wrong number of genes, or transcript names fail to match

Cause: The annotation version in tx2gene differs from the one used to build the Salmon index, or the transcript names carry version numbers.

Fix: Use the same annotation version for both, and set ignoreTxVersion = TRUE.

The number selected at padj < 0.05 does not match the significant count in summary

Cause: results() defaults to alpha = 0.1, and independent filtering is optimised for that value.

Fix: If your final threshold is 0.05, write results(..., alpha = 0.05).

After removing samples or filtering genes and rerunning, the output says using pre-existing size factors

Cause: Samples were removed from an object that had already run DESeq(), so DESeq2 kept the old size factors. This page got 946 differential genes that way, and 951 when the object was rebuilt.

Fix: Start again from DESeqDataSetFromMatrix.

Error: type='apeglm' shrinkage only for use with 'coef'

Cause: apeglm only accepts coef, not contrast. You also hit this when the target comparison is not in resultsNames(dds).

Fix: Relevel the reference level and run nbinomWaldTest to create the new coefficient; or use type = "ashr", which accepts contrast and needs the ashr package.

lfcShrink(dds, contrast = c("condition", "drugB", "drugA"), type = "ashr")
Batch is not treated as a category in the model, so the coefficients make no sense

Cause: batch is numeric, so it is treated as a continuous variable.

Fix: Convert it to a factor before putting it in the design.

coldata$batch <- factor(coldata$batch)
Counts were rewritten with ComBat or removeBatchEffect before DESeq2, and the results do not match expectations

Cause: The output of removeBatchEffect is for PCA and heatmap display only and should not be the input to DESeq2.

Fix: Put the batch in the design (~ batch + condition). If the batch is unknown, estimate surrogate variables with sva and add them to the design as covariates.

DESeq2 fails and reports that the model matrix is not full rank

Cause: Batch and condition are fully confounded, so each batch contains only one group. This is a problem of the experimental design, and analysis cannot fix it.

Fix: Check table(batch, condition) before analysis. If it cannot be fixed, state the design limitation in the report.

Error: No gene can be mapped

Cause: There are three common causes: the input is SYMBOL but keyType defaults to kegg (Entrez); the input is a data.frame rather than a character vector; or the species does not match the annotation package. An overly strict threshold that leaves the list empty produces the same error.

Fix: Convert genes to Entrez IDs before input, pass a character vector, keep the species consistent with the annotation package, and check that the list is not empty.

The enrichment input has far fewer genes than the differential list, or the same gene is counted twice

Cause: In airway, 13.5% of genes have no Entrez ID, mostly lincRNA and pseudogenes; bitr’s one-to-many matches return duplicate rows.

Fix: Use mapIds(multiVals = "first") to keep one ID per gene, then unique(); and state the loss rate in the methods.

enrichKEGG hangs for a long time or fails to connect

Cause: enrichKEGG downloads KEGG data live in each new R session, so it hangs when the network is unavailable.

Fix: Use a local KEGG.db; see the choice “When KEGG access is unstable”.

The enrichment table has results, but barplot or dotplot fails with 'x' is NULL so the result will be NULL

Cause: A KEGG.db built with an older version lacks pathway descriptions (Description). Many posts blame an overly strict threshold, but the real cause is the missing Description.

Fix: Run head(ekk$Description) to check. If it is empty, rebuild the local package with createKEGGdb 0.0.5; the package built on this page has a complete Description.

KEGG download still fails after setting the download method with R.utils::setOption

Cause: In clusterProfiler 4.18.4, KEGG downloads are done by yulab.utils::yread calling readLines, and the source no longer reads the clusterProfiler.download.method option.

Fix: Use a system proxy, or switch to a local KEGG.db.

Error: The package "gridExtra" is required for tableGrob2()

Cause: The pvalue_table argument of gseaplot2 needs the gridExtra package.

Fix: Install gridExtra. Make the figure at least 10 inches wide so the table is not cut off.

msigdbr warns that the category argument is deprecated and cannot find the entrez_gene column

Cause: From msigdbr 10.0, category became collection, and the Entrez column changed from entrez_gene to ncbi_gene.

Fix: Use collection = "H" and ncbi_gene as in the code on this page. For mouse data use db_species = "MM".

GSEA warns that nPerm is not recommended

Cause: The current version uses fgsea’s multilevel sampling, so the number of permutations is no longer set with nPerm.

Fix: Remove the nPerm argument and set seed = TRUE.

The same data gives different numbers of significant terms across runs, for example 210 and 216

Cause: Without a seed, or with a different seed each time, results change. Small changes to the input also shift borderline results: on this page, reusing old size factors (946 differential genes) and rebuilding the object (951) changed the significant gseGO terms from 230 to 198.

Fix: Set seed = TRUE to fix the seed. In the paper, discuss terms with p.adjust between 0.03 and 0.07 as unstable results.

Very few pathways are significant in GSEA, or Inf values appear

Cause: When ranking by sign(log2FC) × -log10(pvalue), very significant genes reach values in the hundreds, so a few genes dominate the enrichment score; p = 0 gives Inf.

Fix: Rank by the stat column from DESeq2. On this page, ranking by stat gives 15 significant hallmark sets, against 1 for sign × -log10(p).

gseGO returns only 2 significant terms

Cause: Ranking only the differential genes breaks the premise of GSEA and removes the background. Ranking all genes gives 198 terms on this page.

Fix: Rank all tested genes.

Results differ in direction or number from the GSEA desktop version

Cause: The ranking input, permutation method, gene set size, gene IDs, ties, random seed and gene set version can all differ.

Fix: Align each item; see “Aligning with the GSEA desktop version when results differ” in the reference section.

ggplot warns about missing values and drops points, or -log10 produces Inf

Cause: Genes with NA padj were not removed. Very significant genes can have padj underflow to 0, which becomes Inf after -log10.

Fix: Remove NA first with df <- df[!is.na(df$padj), ]; replace 0 with the smallest non-zero value and say so in the legend.

The significant points on the volcano plot do not match the list in the text

Cause: The volcano plot’s y axis uses pvalue, but the filter uses padj.

Fix: Use padj for both the y axis and the threshold line, matching the filter.

The text says a pathway is “activated”, but the figure shows ORA of up-regulated genes only

Cause: Enrichment was run in one direction only, which cannot show the direction of a pathway.

Fix: Use the NES from GSEA to judge direction, or run ORA separately on up- and down-regulated genes and state this in the text.

The main figure shows a pathway curve with p.adjust above 0.05, described as “significantly enriched”

Cause: A non-significant pathway was placed in the main figure.

Fix: Show only significant pathways in the main figure, and describe non-significant results as exploratory.

The number of differential genes in the text differs from the row count of the supplementary table

Cause: After SYMBOL de-duplication or ID conversion removed some genes, the number in the text was not updated.

Fix: Count from the final result table and use the same number in the text and the supplementary table.

References

FAQ

DESeq2, edgeR and limma give different numbers of DE genes. Which should I use?

Pick one and state the version. On airway they gave 951, 1183 and 1145 genes, with 910 in common; the differences are borderline genes with |log2FC| near 1. With 3–6 replicates per group, DESeq2 and edgeR both fit; use limma-voom for many samples or complex designs, and limma for microarrays.

Can I do differential expression without biological replicates?

Not with trustworthy significance. DESeq2 errors out; edgeR lets you fix a BCV (0.4 for human), but changing the BCV from 0.1 to 0.4 took significant genes from 1645 to 17 here. Without replicates, report a log2FC ranking and candidate genes, and validate experimentally.

Do I have to set a background (universe) for enrichment analysis?

Yes. The universe should be the genes actually detected and tested (non-NA padj in DESeq2 results). Here, enrichKEGG without a universe went from 17 to 45 significant pathways, and the extras were common pathways highly expressed in the tissue.

Should the GSEA FDR cutoff be 0.25 or 0.05?

With clusterProfiler or fgsea, use p.adjust, usually 0.05. The 0.25 cutoff is Broad GSEA's exploratory threshold for its permutation FDR q-value; if you borrow it for R results, cite its origin and treat findings as hypotheses.

Should I rank genes for GSEA by log2FC or by stat?

Use the DESeq2 stat column (Wald statistic). On hallmark sets here, ranking by stat gave 15 significant sets, apeglm-shrunken log2FC gave 3 and sign×-log10(p) gave 1. If you rank by log2FC, it must be the shrunken value.

enrichKEGG is slow or cannot connect from China. What can I do?

When you have network access, run createKEGGdb::create_kegg_db("hsa") to build a local KEGG.db (7–9 s here), install it, and add use_internal_data = TRUE to enrichKEGG to run offline with the same results. Do not use the old Bioconductor KEGG.db, whose data stop in 2012.

Hand differential expression and enrichment analysis to Scientify

The science agent installs R and Bioconductor packages in an isolated cloud computer and follows this page through DESeq2, lfcShrink, GO/KEGG enrichment with a background and GSEA. It outputs result tables and plots and keeps the scripts, package versions and KEGG data date for reproduction. New users get USD 5 of free credit.