Session 5 : Enrichment analysis of Differentially Expressed Genes

Advanced R-course 2026

Dr. Debasish Mukherjee

Bioinformatics Core Facility CECAD

2026-11-27

Slides & Code

  • [f] Full screen
  • [o] Slide Overview
  • [c] Notes
  • [h] help

git repo

R-Advanced


Clone repo

git clone https://github.com/CECADBioinformaticsCoreFacility/Advanced_R_course_2026.git


Slides Directly

https://cecadbioinformaticscorefacility.github.io/Advanced_R_course_2026/

Session 5 :: Enrichment Analysis

Enrichment Analysis

What to do with the DE genes?

Are these genes associated with particular biological functions, pathways, or processes more than we’d expect by chance?

Advantages:

  • Biological interpretability
  • Increased statistical power
  • Cross-study reproducibility
  • Broad multi-omics compatibility
  • Generate new hypotheses

Limitations:

  • Dependence on database completeness
  • Pathway overlap and redundancy
  • Sensitivity to background selection
  • Assumption of feature independence

Main Approaches

  • Over-representation analysis (ORA)
  • Gene Set Enrichment Analysis (GSEA) / Functional Class Scoring (FCS)
  • Pathway Topology-based methods

Categorization of genes

Note

A category is over-represented if it makes up a bigger share of your gene list than it does in the background set — and the p-value says how likely that is by chance.

Regrouping genes together in meaningful sets based on:

  • involvement in a pathway
  • presence in a specific cellular location
  • shared molecular function
  • other categorizations …
Symbol Description
\(N\) Total number of genes (universe)
\(M\) Number of DE genes (your list)
\(k\) Number of genes in a category(GO term)
\(n\) Number of DE genes found in that category

Categorized gene sets : Databases

Human curated:

  • Gene Ontology (GO)
  • Biological Pathways (Reactome, KEGG, WikiPathways)

Domains / Patterns:

  • Protein functional domains (SMART, InterPro)
  • Transcription factor regulated (AnimalTFDB, JASPAR)

Experimental:

  • Co-expressed genes (GeneFriends, COXPRESdb)
  • Interactions (STRING, BioGRID)
  • Hits from other studies

Molecular Signatures Database (MSigDB) is a popular resource that compiles many gene sets from various sources.

Gene Ontology (GO)

  • GO provides a controlled vocabulary to describe gene functions.

  • Three main domains:

    • Biological Process (BP) – pathways and larger processes
    • Molecular Function (MF) – biochemical activities
    • Cellular Component (CC) – where functions occur

Over-representation analysis (ORA) Steps …

  1. Define a list of DE genes (e.g., based on p-value and fold-change thresholds)
  2. For each gene set(category), count how many DE genes are in the set
  3. Compare this to the expected number based on the background set
  4. Use statistical tests (e.g., Fisher’s exact test, hypergeometric test) to determine if the overlap is greater than expected by chance
  5. Adjust for multiple testing (e.g., Benjamini-Hochberg correction)
  6. Interpret results to identify significantly enriched categories

Gene set (category) Size \(k/N\) DE genes \(n/M\) Overrepresented ?
Category 1 59/20000 45/2000 Yes/No
Category 2 150/20000 30/2000 Yes/No
Category 3 300/20000 10/2000 Yes/No
… … … …
Symbol Description
\(N\) Total number of genes (universe)
\(M\) Number of DE genes (your list)
\(k\) Number of genes in a category(GO term)
\(n\) Number of DE genes found in that category

Step 1/6 · Define your list of DE genes

I have 1,086 “significant” genes — how was 1,086 decided?

  • This list is \(M\) in the hypergeometric test — every later step inherits its choices
  • Typical thresholds:
    • adjusted p-value (FDR) ≤ 0.05 (sometimes 0.1)
    • \(|log_2\) fold change\(|\) ≥ 0.5–1 (optional, effect size)
  • The fold-change filter is a judgment call:
    • with it: only biologically plausible effects, smaller \(M\)
    • without it: tiny but real changes included, larger \(M\)
res <- results(dds) |> as.data.frame()

uni_genes <- res |>
  filter(!is.na(padj)) |>
  rownames()

de_genes <- res|> 
  filter(!is.na(padj),padj <= 0.05)|>
  rownames()

print(paste("Universe:",length(uni_genes)))
[1] "Universe: 20729"
print(paste("DE genes:",length(de_genes)))
[1] "DE genes: 1086"

Note

Choose thresholds before looking at enrichment results — filtering on what “looks interesting” after the fact biases everything downstream.

Step 2/6 · Count the overlap in each gene set

102 of my 1,086 DE genes are in “regulation of immune effector process”. Is that a lot?

Not yet — 102 means nothing until you know how big the set is. For every gene set, you count how many of your DE genes fall in it:

Gene set (category) Size \(k/N\) DE genes \(n/M\)
regulation of immune effector process 401/15,893 102/987
regulation of lymphocyte activation 491/15,893 113/987
leukocyte cell-cell adhesion 412/15,893 96/987

Important

Where did 987 come from? My list has 1,086 genes. enrichGO silently drops genes it can’t map to the OrgDb and genes with no BP annotation: 1,086 → 987 (DE list), 20,729 → 15,893 (universe). The test runs on the filtered lists. Always check: ego_result@result$DESize and $UniverseSize — if they differ from your input lengths, the filter did its work.

Warning

Gene IDs must match the database key type. enrichGO(..., keyType = "SYMBOL") means your list has to contain gene symbols. A list of Entrez IDs “succeeds” with 0 hits — the most common silent failure in ORA.

Step 3/6 · Compare to the expected number

If DE genes fell into gene sets at random, how many would I expect to see in “regulation of immune effector process”?

The background (universe) of \(N = 15893\) genes contains \(k = 401\) regulation of immune effector process genes. If my \(M = 987\) DE genes are a random draw from the universe, the expected overlap is:

\[ E = \frac{M \times k}{N} = \frac{987 \times 401}{15893} = 24.9 \]

I observed 102 — about 4 times the expectation. Now I need to know whether that gap is statistically significant.

Note

The choice of background changes the answer: genome-wide (\(N = 20000\)) vs. genes detected in your experiment (e.g., \(N = 15893\)). The detected-genes background removes detection bias; pick one and be consistent.

Step 4/6 · Test significance (hypergeometric / Fisher)

102 observed vs 24.9 expected — but is that gap luck or signal?

The comparison is laid out as a 2×2 contingency table:

In gene set Not in gene set
DE 102 885
Not DE 299 15594

Fisher’s exact test asks: given the margins are fixed, what is the probability of an overlap at least as extreme as 102 by chance?

Mathematically, that is the hypergeometric test — “drawing \(M = 987\) balls from an urn of \(N = 15893\) that holds \(k = 401\) marked balls”:

\[ P(X \geq n) = \sum_{i=n}^{M} \frac{\binom{k}{i} \, \binom{N-k}{M-i}}{\binom{N}{M}} \]

Tip

Same test, different names: Fisher’s exact test on the contingency table ≡ hypergeometric test on the urn problem. The next two slides work through it in R.

Example in R

# Define parameters
N <- 15893   # Total number of genes
k <- 401     # Genes in the GO term
M <- 987    # Total number of DE genes
n <- 102      # DE genes in the GO term

# = UniverseSize / DESize from the enrichGO result, after OrgDb + BP filtering

# Calculate p-value using hypergeometric test
p_value <- phyper(q = n - 1,      # q = x-1 for upper tail
                  m = k,          # number of white balls in population
                  n = N - k,      # number of black balls in population
                  k = M,          # number of draws
                  lower.tail = FALSE)

print(paste("P-value:", p_value))
[1] "P-value: 4.25016412569541e-36"

Interpreting the P-Value

This p-value indicates the probability of observing 102 or more DE genes in the GO term by chance. A low p-value (e.g., < 0.05) suggests that the GO term is significantly over-represented among the DE genes.

Important

Remember to adjust for multiple testing when evaluating p-values across many GO terms.

Step 5/6 · Correct for multiple testing

I just tested 4,949 gene sets at \(p < 0.05\). How many “significant” sets should I expect — even if the experiment was perfect?

\[ 4949 \times 0.05 = 247.45 \approx 247 \text{ false positives by chance alone} \]

So a raw p-value threshold guarantees a pile of false discoveries. Instead, control the False Discovery Rate with the Benjamini–Hochberg (BH) procedure:

  1. Rank all p-values: \(p_{(1)} \leq p_{(2)} \leq \dots \leq p_{(m)}\)
  2. Find the largest \(k\) with \(p_{(k)} \leq \frac{k}{m} \cdot q\)
  3. Call all p-values up to \(k\) significant at FDR level \(q\)

Interpretation: at FDR 0.05, roughly 5% of the declared significant sets are expected to be false positives.

Toy example with \(m=8\) tests — in your run \(m\) = 4,949, same procedure.
Rank (\(i\)) GO term Raw pvalue Raw BH: \(p \cdot \frac{m}{i}\), \(m=8\) Cumulated p.adjust (running min)[BH] FDR < 0.05?
1 Cell Cycle 0.002 0.002 × 8/1 = 0.016 0.016 Yes
2 DNA Replication 0.008 0.008 × 8/2 = 0.032 0.032 Yes
3 Mitosis 0.012 0.012 × 8/3 = 0.032 0.032 Yes
4 Apoptosis 0.025 0.025 × 8/4 = 0.050 0.050 Yes
5 Metabolism 0.250 0.250 × 8/5 = 0.400 0.320 No
6 Lipid transport 0.240 0.240 × 8/6 = 0.320 0.320 No
7 Protein folding 0.600 0.600 × 8/7 = 0.686 0.686 No
8 Circadian rhythm 0.900 0.900 × 8/8 = 0.900 0.900 No

Step 6/6 · Interpret the results

The table says “regulation of immune effector process, padj = 2.1e-32”. Now what?

  • Read each row:
    • ID / Description — which term
    • pvalue → p.adjust — use the adjusted value
    • GeneRatio — your DE genes in the term / all DE genes
    • geneID — which of your DE genes drove the term
    • BgRatio — genes in the term / all background genes
  • Watch for redundant clusters of related terms (remember the GO DAG?) — summarize before you interpret
  • Sanity check: does the biology fit your system? If the top terms are “ribosome” and “oxidative phosphorylation” after a treatment you never expected to touch metabolism, re-check your data first
  • Then: literature validation → experimental follow-up

Tip

Significant ≠ important. A large, well-powered but tiny-effect process can out-test a small, central one. Let the biology, not just the p-value, drive your conclusions.

GO as a Directed Acyclic Graph (DAG)

  • GO terms form a hierarchical structure.

  • Each GO term may have:

    • Parent terms (more general)
    • Child terms (more specific)
  • Relationships include:

    • is_a: subclass
    • part_of: component of a larger process
  • Hierarchy is not strictly a tree; terms can have multiple parents.

Implications of the GO DAG

  • A gene annotated to a specific child term is also annotated to all its parent terms.
  • GO enrichment results often show clusters of related terms.
  • Understanding the hierarchy helps interpret redundancy.

How GO Hierarchy Affects ORA

Annotation Propagation

  • Because children inherit from parents:

    • Broad parent terms often have many genes, reducing specificity.
    • Specific child terms may give more targeted insights.

Redundancy in Enrichment Results

  • ORA may flag clusters of related terms.
  • This is due to overlapping gene sets across the DAG.
  • Redundant terms can complicate interpretation.

Strategies to Manage Redundancy

  • Use tools that:

    • Summarize GO terms (e.g., REVIGO)
    • Prune the DAG (e.g., parent-child approaches)
    • Cluster enriched terms based on similarity
  • Focus on most specific significant terms for clearer insights.

  • packages like topGO, ClueGO, GO-Bayes, GO-Elit etc. help address hierarchy issues.

GO Hierarchy: Takeaways

  • GO is a hierarchical DAG, not a simple tree.
  • Term relationships propagate annotations upward.
  • ORA enrichment results depend strongly on GO hierarchy.
  • Awareness of hierarchy helps with better interpretation and reduction of redundancy.

clusterProfiler

  • Comprehensive R package for functional enrichment analysis
  • Supports GO, KEGG, Reactome, Disease Ontology, and custom gene sets
  • Implements ORA and GSEA methods
  • Provides visualization functions (dot plots, bar plots, enrichment maps)
  • Integrates with other Bioconductor packages (e.g., DESeq2, edgeR)

Example: ORA with clusterProfiler

# Load necessary libraries
library(clusterProfiler)
library(org.Mm.eg.db)
library(ggplot2)
library(dplyr)
library(DESeq2)
library(qs2)

set.seed(420)

dds <- qs_read("dds_all_genotype.qs")
uni_genes <- results(dds) |> as.data.frame() |>
    filter(!is.na(padj)) |>
    rownames()
de_genes_up <- results(dds) |> as.data.frame() |>
    filter(!is.na(padj),padj <= 0.05, log2FoldChange > 0)|>
    rownames()
de_genes_dn <- results(dds) |> as.data.frame() |>
    filter(!is.na(padj),padj <= 0.05, log2FoldChange < 0)|>
    rownames()

ego_result_up <- enrichGO(gene = de_genes_up,
                       universe = uni_genes,
                       OrgDb = org.Mm.eg.db,
                       keyType = "SYMBOL",
                       ont = "BP",
                       pAdjustMethod = "BH",
                       pvalueCutoff = 0.05,
                       qvalueCutoff = 0.2,
                       readable = TRUE)
# View results
#DT::datatable(head(ego_result_up))

# Visualize results
barplot(ego_result_up, font.size=14) + 
    ggtitle("GO Enrichment Analysis - Upregulated Genes : Barplot")

Visualisation with enrichplot - Dotplot

dotplot(ego_result_up, showCategory=10, font.size=14) + 
    ggtitle("GO Enrichment Analysis - Upregulated Genes : Dotplot")

Visualisation with enrichplot - Enrichment Map

# Add similarity matrix to the termsim slot of enrichment result
ego_result_up <- enrichplot::pairwise_termsim(ego_result_up)

# Enrichmap clusters the 30 most significant (by padj) GO terms
# to visualize relationships between terms
emapplot(ego_result_up, showCategory = 30) + 
    ggtitle("GO Enrichment Analysis - Upregulated Genes : Enrichment Map")

Visualisation with enrichplot - Cnetplot

cnetplot(ego_result_up, showCategory = 20, foldChange = NULL) + 
    ggtitle("GO Enrichment Analysis - Upregulated Genes : Cnetplot")

Visualisation with Treemap plot

library(rrvgo)

simMatrix <- calculateSimMatrix(ego_result_up$ID,
                                orgdb="org.Mm.eg.db",
                                ont="BP",
                                method="Rel")

scores <- setNames(-log10(ego_result_up$qvalue), ego_result_up$ID)

reducedTerms <- reduceSimMatrix(simMatrix,
                                scores,
                                threshold=0.7,
                                orgdb="org.Mm.eg.db")

treemapPlot(reducedTerms)

Things to Remember

Directional Gene Lists

  • Separate upregulated and downregulated genes
  • Perform enrichment analysis on each list separately
  • Compare enriched categories between up and downregulated genes
  • Provides insights into distinct biological processes affected

One search :

  • Higher power (more genes)
  • Lower enrichment
  • Mixed effects (pathways)

Two searches:

  • Easier interpretation
  • Less power
  • Higher enrichment

Note

  • Consider biological context and research question when choosing approach
  • Using a background list can make a huge difference
  • Validate findings with additional experiments or literature review
  • Combine with other analyses (e.g., network analysis) for deeper insights
  • handle redundancy

Quiz Time!

Quiz Time!