Gene Set Enrichment Analysis (GSEA)
Bioinformatics Core Facility CECAD
2025-11-20
git clone https://github.com/CECADBioinformaticsCoreFacility/Advanced_R_Course_2025.git
https://github.com/CECADBioinformaticsCoreFacility/Advanced_R_course_2025
Session 6 :: Gene Set Enrichment Analysis
Input:
Algorithm:
Output:
The ranking metric:
This can be anything, but in the context of DESeq2 analysis two choices prevail:
# NOT padj !The per-step increment/decrement:
[Increment and decrement are in addition weighted by the total number of hits and misses in the ranked gene list.]
Permutations are time-consuming, but \(\boldsymbol{\alpha} \boldsymbol{\neq} \mathbf{0}\) is a conceptual improvement: it allows to weight a match at position i by \(|s_i|\) .
Sample Permutation:
for n = 1:N do
Pro:
it fits naturally with the typical experimental question:it uses the native gene sets
Con:
TAKES A LOT OF TIME!Gene Set Permutation
for n = 1:N do
for each gene set g do
\(\square\)
\(\square\)
Pro:
MUCH FASTER than sample permutation (dependent on the implementation)today the de facto standard
Con: (-> next slide!)
Con:
Gene Set Permutation is justified by the following line of argument:
The weak point of this line of argument: gene-gene correlations!
Yet .. in practice, Gene Set Permutation GSEA does discover interesting gene sets,
-- and it is fast!
Several R packages either use or implement variants of the Fast Gene Set Enrichment Analysis (FGSEA) algorithm, which implements a fast approximation to the naive gene-sampling approach of Gene Set Permutation:
fgsea is the original implementation corresponding to the paper (see above link)clusterProfiler uses fgsea in several database interfacing packages like gseGO, gseKEGG, and othersBoth packages are also available on Bioconductor.
This is the original algorithm corresponding to the Subramanian et al. 2005 paper. The original idea focused on Sample Permutation, arguing that Gene Set Permutation overestimates significance levels by ignoring gene-gene correlations. However Gene Set Permutation was also provided as an option, for cases with too few samples to allow a meaningful Sample Permutation.
An R package version of the software used to be distributed by MSigDB (Broad Institute), however this has been recently discontinued. The code is still provided here, but with the disclaimer R-GSEA remains unsupported by the GSEA-MSigDB Team. MSigDB provides its implementation as a Java application.
piano is another Bioconductor package, first published in 2013. It offers GSEA with both Sample Permutation and Gene Set Permutation, among a range of other methods.
For the Sample Permutation test, the user must pre-compute all permuted data runs. A brute force computation on my laptop of DESeq2 results for 460 genotype permutations of the practice dataset took about 1 day (this could surely be improved). The piano result with this input was superficially similar to an fgsea Gene Set Permutation result, which takes a few minutes. This seems to suggest that sample permutation on a large dataset may not be worthwhile – but one would need to dig deeper to see whether there are benefits of this statistically more sound, but time consuming method.
We have seen that the “~ genotype” model yields too few significant genes to produce a significant ORA result with the full matrix, and in most cases also after subsetting by tissue.
GSEA may be more sensitive to a weak signal, because it uses a pre-ranked list of all genes of interest, rather than a pre-selected set of (significant) genes. Prioritization criteria are coded in the ranking metric (usually the degree of differential expression between experimental groups).
Important
The consistent clustering of a gene set’s members in a sub-significant region of the ranked list may be a stronger hint at a biological role of the gene set than a few isolated member genes with significant differential expression.
We will see that a pure “~ genotype” effect, without explicitly modeling other factors, can indeed manifest in the form of exactly this sub-significant non-randomness.
We subset the full data matrix to retain liver samples only (see function subset_counts() in this script ). This removes the excessive variance due to tissue differences.
library("org.Mm.eg.db")
dds_liver <- subset_counts(dds_genotype,level_list=list(tissue="liver"),
include=TRUE, refit=TRUE)
res_liver.genotype <- results(dds_liver,
name="genotype_nmrhas2_vs_creer"
)
table(res_liver.genotype$padj <= 0.05,
useNA="ifany")
FALSE TRUE <NA>
19222 18 13664
Yet, only 18 genes are significantly differently expressed between transgenic and wildtype animals – only two more genes than with the full dataset.
Still it is possible that this small group of genes belongs to shared, meaningful pathways.
Let’s try an ORA analysis first (see Session 5):
liver_sig_genes_up <-
res_liver.genotype |> as.data.frame() |>
filter(!is.na(padj),padj <= 0.05, log2FoldChange > 0)|>
tibble::rownames_to_column("symbol") |> pull(symbol)
liver_sig_genes_dn <-
res_liver.genotype |> as.data.frame() |>
filter(!is.na(padj),padj <= 0.05, log2FoldChange < 0)|>
tibble::rownames_to_column("symbol") |> pull(symbol)
universe <-
res_liver.genotype |> as.data.frame() |>
filter(!is.na(padj)) |> rownames()
## How many significantly UP-regulated terms were found per GO ontology?
sapply(ego_liver_genotype_0.05_up,
function(x) x |> #as.data.frame() |>
filter(p.adjust <= 0.05) |> nrow()
) BP MF CC
228 25 0
Looks as if quite some terms of the Biological Process ontology are up-regulated … however …
## How many significantly DOWN-regulated terms were found per GO ontology?
sapply(ego_liver_genotype_0.05_dn,
function(x) x |> #as.data.frame() |>
filter(p.adjust <= 0.05) |> nrow()
)BP MF CC
0 0 0
Not a single term in any ontology!
## How many significant terms were found per GO ontology?
sapply(gse_liver_genotype_0.05,
function(x) x |> #as.data.frame() |>
filter(p.adjust <= 0.05) |> nrow()
) BP MF CC
1385 125 120
Indeed: GSEA finds much more significant terms!
The “NES” column in the GSEA result table contains the Normalized Enrichment Score. Given our ranking by the Wald test statistic, a positive NES suggests up-regulation of its genes in nmrHAS2 compared to creER, while a negative NES suggests down-regulation.
## Number of significant terms with positive NES ..
sig_up <-
sapply(gse_liver_genotype_0.05,
function(x) x |> #as.data.frame() |>
filter(p.adjust <= 0.05, NES > 0),
simplify=FALSE
)
sapply(sig_up, nrow) BP MF CC
376 40 30
## based on how many genes?
sapply(sig_up,
function(x) ## core_enrichment is the equivalent of geneID in GSEA
sapply(x$core_enrichment,
strsplit,'/'
) |>
unlist() |> unique() |> length()
) BP MF CC
2267 670 920
The “NES” column in the GSEA result table contains the Normalized Enrichment Score. Given our ranking by the Wald test statistic, a positive NES suggests up-regulation of its genes in nmrHAS2 compared to creER, while a negative NES suggests down-regulation.
## Number of significant terms with negative NES ..
sig_dn <-
sapply(gse_liver_genotype_0.05,
function(x) x |>
filter(p.adjust <= 0.05, NES < 0),
simplify=FALSE)
sapply(sig_dn, nrow) BP MF CC
1009 85 90
## based on how many genes?
sapply(sig_dn,
function(x) ## core_enrichment is the equivalent of geneID in GSEA
sapply(x$core_enrichment,
strsplit,'/'
) |>
unlist() |> unique() |> length()
) BP MF CC
2481 1372 1534
A typical “GSEA plot”, as introduced by the Broad Institute implementation, can be drawn by enrichplot::gseaplot2().
gseaplot2() draws the ES curve of one or more gene sets. Let’s draw the first sig_up and the first sig_dn term:
Observe
With more than ~5 ES curves overplotted on the same canvas, detailed GSEA plots become hard to read. Function emapplot() provides a bird’s eye view, completely disregarding the details on why individual terms are significant, but rather plotting a semantic similarity graph of many significant terms at once.
For sig_up:
[see next slide for output]
The top 150 up-regulated terms are characterized by a dense metabolic cluster plus more loosely connected terms, often ER-related.
With more than ~5 ES curves overplotted on the same canvas, detailed GSEA plots become hard to read. Function emapplot() provides a bird’s eye view, completely disregarding the details on why individual terms are significant, but rather plotting a semantic similarity graph of many significant terms at once.
For sig_dn:
[see next slide for output]
The top 150 down-regulated terms are dominated by a large, dense cluster of immune terms (mostly regulatory and signaling) and a smaller cluster of terms related to immune cell migration.
NOTE: there are much more significant “down” than “up” terms. As a consequence a hard threshold of 150 terms cuts at a much smaller p.adjust value in the “down” list than in the “up” list!
The “core_enrichment” genes of a term contribute most to the deviation of the running sum from zero. We would like to see where they are located in the distribution of DESeq2 adjusted p-values.
Plotting of detailed information on individual terms’ genes is restricted to a few terms at a time. Here is a function to ease inspecting multiple such subsets: it returns a random subset of terms with GSEA p.adjust in a specified numerical range, which can later serve as plotting input:
This (long! – scroll down) function draws the plots:
It calls term_by_GSEA_p.adjust(), then for each selected term (1) plots DESeq2 “stat” (GSEA’s rank metric) vs -log10(DESeq2 “padj”), and (2) distinguishes the core enrichment genes (“core”) and the remaining genes (“bg” = background) by color.
plot_terms <-
function(res_DE, # a DESeqDataSet object
res_GSEA, # a gseaResult object
min_p=1e-10, max_p=0.05, nterms=6
) {
terms <- ## select 6 terms at a time
term_by_GSEA_p.adjust(res_GSEA,
min_p = min_p,
max_p = max_p,
nterms= nterms)
# get the Descriptions of the terms:
D <- setNames(res_GSEA[terms,"Description"],
terms)
# get the adjusted GSEA p-values of the terms:
P <- setNames(res_GSEA[terms,"p.adjust"],
terms)
# get the NES of the terms:
N <- setNames(res_GSEA[terms,"NES"],
terms)
# get the core_enrichment genes of the terms:
C <- setNames(res_GSEA[terms, "core_enrichment"],
terms)
# the ranking metric used for GSEA is stored in slot @geneList of the gseaResult object
L <- res_GSEA@geneList
# the DESeq2 result in the same order as L:
res_DE <- res_DE[names(L),] |> as.matrix()
# converting to matrix() above allows to extract a *named* column:
minusLog10_padj <- -log10(res_DE[,"padj"])
# construct the ggplot() input data.frame():
df <-
Reduce(rbind,
lapply(terms,
function(t) data.frame(
term = paste0(t, "\n(",D[t],")\n",
"p.adjust=",signif(P[t],digits=2)),
x = L,
minusLog10_padj = minusLog10_padj,
core_enrichment =
factor(ifelse(
names(minusLog10_padj) %in% strsplit(C[t],"/")[[1]],
"core", "bg"
))
)
)
)
colors <- c(bg="darkgrey",core="orange")
sizes <- c(bg=0.1,core=1)
ggplot(df) +
geom_point(aes(x=x,y=minusLog10_padj, color=core_enrichment, size=core_enrichment)) +
geom_hline(yintercept = -log10(0.05)) + # add indicator line for p=0.05
scale_color_manual(values=colors) +
scale_size_manual(values=sizes) +
scale_x_reverse() + # plot x-axis from positive to negative values
theme(plot.title = element_text(size=10)) +
xlab("stat (DESeq2 Wald statistic)") +
ylab("-log10(DESeq2 padj)") +
facet_wrap(~term) # one plot per term
}A sample of GSEA up-regulated terms: More significant terms are more clustered and/or include significant DE genes.
A sample of GSEA down-regulated terms: More significant terms are more clustered and/or include significant DE genes.