R Advanced Course 2025

Gene Set Enrichment Analysis (GSEA)

Ulrike Göbel

Bioinformatics Core Facility CECAD

2025-11-20

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_2025.git


Slides Directly

https://github.com/CECADBioinformaticsCoreFacility/Advanced_R_course_2025

Session 6 :: Gene Set Enrichment Analysis

Gene Set Enrichment Analysis – The Basic Algorithm

Input:

  • a ranked gene list
  • one gene set (e.g. GO term) at a time

Algorithm:

  • Step 1: Mark members of the gene set in the list
  • Step 2: “Walk” down the list from top to bottom, and do at each list position:
    • if the current gene is in the gene set, increment a running sum
    • if it is not, decrement the sum

Output:

  • Enrichment Score (ES): the largest absolute sum value encountered on the walk
  • Normalized Enrichment Score (NES): The ES corrected for the effect of gene set size

Variants and Implementations – Counting Options

  • The ranking metric:

    This can be anything, but in the context of DESeq2 analysis two choices prevail:

    • \(-log10(pvalue) * sign(log2FoldChange\) # NOT padj !
    • the Wald statistic (the \(stat\) column in a result table)
  • The per-step increment/decrement:

    • The general form is
      • increment: \(|s_i|^{\alpha}\), where \(s_i\) is the ranking metric at position i
      • decrement: \(-1\)

      [Increment and decrement are in addition weighted by the total number of hits and misses in the ranked gene list.]

    • If \(\boldsymbol{\alpha} \mathbf{\; = 0}\), then the expression reduces to simple counting of both hits and misses (the basic algorithm)  
      In this case the ES follows a Kolmogorov-Smirnov Null distribution, which directly yields p-values.
    • If \(\boldsymbol{\alpha} \boldsymbol{\neq} \mathbf{0}\), then a Null distribution of the ES must be constructed by permutations.

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|\) .

Variants and Implementations – Permutations Options

 

Sample Permutation:

for n = 1:N do

  • randomly shuffle the dataset’s sample labels
  • re-compute the ranking metric, using the shuffled dataset (this means to re-run DESeq2!)
  • re-compute the GSEA scores, using the re-computed ranking metric

 

Pro:

  • it fits naturally with the typical experimental question:
    Do different sample labels = different experimental conditions imply differential use of functional gene sets?
  • it uses the native gene sets

 

Con:

  • For a reasonably large N (>= 1000) it TAKES A LOT OF TIME!

Variants and Implementations – Permutations Options

Gene Set Permutation

for n = 1:N do

for each gene set g do

  • construct a randomized copy, by drawing overlap(g, L) genes from the ranked gene list L

\(\square\)

  • re-compute the GSEA scores , using the randomized gene sets and the original dataset

\(\square\)

 

Pro:

  • MUCH FASTER than sample permutation (dependent on the implementation)
  • therefore it is today the de facto standard

 

Con: (-> next slide!)

Variants and Implementations – Permutations Options

Con:

Gene Set Permutation is justified by the following line of argument:

  • a random subset of the ranked genes is not expected to be significantly differentially expressed between experimental conditions
  • a Null distribution of the GSEA scores of a native gene set S can therefore be constructed like so:
    • randomly draw a subset of size(S) from the ranked genes and determine its GSEA score
    • repeat N times (N large)
  • use this distribution to define a p-value of “no differential expression” for S

The weak point of this line of argument: gene-gene correlations!

  • native gene sets are co-evolved functional units, which are often induced or repressed as a whole
  • in native sets, it is not unlikely to see several or many member genes vary in the same direction between conditions
  • in random sets, this is much more unlikely
  • hence p-values from Gene Set Permutation may be inflated: even a moderate differential expression may count as highly significant

Yet .. in practice, Gene Set Permutation GSEA does discover interesting gene sets,  

-- and it is fast!

Variants and Implementations – FGSEA

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 others

Both packages are also available on Bioconductor.

Variants and Implementations – MSigDB GSEA-R

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.

Variants and Implementations – piano

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.

GSEA in Action

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.

GSEA in Action – Subsetting the Data Matrix to Liver Only

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.

GSEA in Action – Try ORA First, For Comparison

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()

 

ego_liver_genotype_0.05_up <-
     runORA(liver_sig_genes_up,universe,org.Mm.eg.db,"SYMBOL")
ego_liver_genotype_0.05_dn <-
     runORA(liver_sig_genes_dn,universe,org.Mm.eg.db,"SYMBOL")

GSEA in Action – Try ORA First, For Comparison

## 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 …

## All terms found are indeed based on a tiny set of genes:
sapply(ego_liver_genotype_0.05_up$BP$geneID,
       strsplit,'/'
       ) |> unlist() |> unique()
[1] "Irs2"   "Bmp2"   "Dnah11" "Nfil3" 
sapply(ego_liver_genotype_0.05_up$MF$geneID,
       strsplit,'/'
       ) |> unlist() |> unique()
[1] "Irs2"   "Bmp2"   "Dnah11"
## All these terms share only 4 genes with our universe, and  
## one or two of these are among the significant genes (see the 
## GeneRatio column). These are very likely spurious matches,   
## especially as the "Description"s look unrelated to liver biology.

GSEA in Action – Try ORA First, For Comparison

## 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!

GSEA in Action – Can It Do Better?

L <- (res_liver.genotype |> as.data.frame() |>
     filter(!is.na(padj)) |> arrange(desc(stat)) |>
     as.matrix())[,"stat"]
gse_liver_genotype_0.05 <- runGSEA(L,org.Mm.eg.db,"SYMBOL")

 

## 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!

GSEA in Action – Can It Do Better?

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 

GSEA in Action – Can It Do Better?

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 

GSEA in Action – Visualizing the Result

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:

enrichplot::gseaplot2(sig_up$BP,
                      geneSetID = sig_up$BP$ID[1], 
                      title = sig_up$BP$Description[1])

enrichplot::gseaplot2(sig_dn$BP,
                      geneSetID = sig_dn$BP$ID[1], 
                      title = sig_dn$BP$Description[1])

Observe

  • Although the adjusted p-values of both terms are highly significant (1.8^{-12} and 3.8^{-31}), the peaks of the ES curves are not very close to the top and the bottom of the ranked list. 
    The main contribution to the peaks surely comes from sub-significant, yet clustering, genes (on the x axis).

GSEA in Action – Visualizing the Result

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:

enrichplot::emapplot(enrichplot::pairwise_termsim(sig_up$BP),
                     showCategory = 150)  

[see next slide for output]

GSEA in Action – Visualizing the Result

 

The top 150 up-regulated terms are characterized by a dense metabolic cluster plus more loosely connected terms, often ER-related.

GSEA in Action – Visualizing the Result

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:

enrichplot::emapplot(enrichplot::pairwise_termsim(sig_dn$BP),
                     showCategory = 150)

[see next slide for output]

GSEA in Action – Visualizing the Result

 

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!

Core Enrichment Genes and DESeq2 Adjusted P-Values

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:

term_by_GSEA_p.adjust <- 
  function(res, # a gseaResult object 
           min_p=1e-10, max_p=0.05, nterms=1) {
    sample((res |> #as.data.frame() |>
           filter(p.adjust >= min_p,
                  p.adjust <= max_p))$ID, ## pull does not work with gseaResult   
           size=nterms, replace=FALSE)
  }

Core Enrichment Genes and DESeq2 Adjusted P-Values

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                    
}

Try it out [output next slide] – do it several times, to get an impression of the variance!

plot_terms(res_DE = res_liver.genotype, 
           res_GSEA = sig_dn$BP, 
           max_p = 0.01,
           nterms = 9)

Core Enrichment Genes and DESeq2 Adjusted P-Values

A sample of GSEA up-regulated terms: More significant terms are more clustered and/or include significant DE genes.

Core Enrichment Genes and DESeq2 Adjusted P-Values

A sample of GSEA down-regulated terms: More significant terms are more clustered and/or include significant DE genes.

Summary

  • Overrepresentation Analysis (ORA) and Gene Set Enrichment Analysis (GSEA) are in many respects complementary approaches to functional enrichment analysis:
    • ORA pre-selects genes (typically based on significant differential expression) and examines the selected list for an over-representation of functional terms
    • GSEA scores one functional term at a time, both by its member genes’ position on a rank metric (which encodes degree and direction of differential expression), and by the degree of clustering of the genes on the metric. Notably a strong clustering of many genes (=high consistency) can make up for a sub-significant position on the metric.
  • For cases with few significant differentially expressed genes (like the nmrHAS2 genotype effect in the liver), GSEA can still recover sub-significant but consistent enrichments:
    • down-regulation of immune terms (in concordance with the study authors)
    • up-regulation of metabolic terms
    • neither of these had been apparent with ORA
  • Caveat: GO terms are embedded in a parent-child network, where “parent terms” (super-concepts) can encompass several “child terms” (sub-concepts). Especially in well-researched areas like the immune system this graph of relationships can be dense. As “children” are by definition similar to their “parents”, they can be expected to cluster in similar areas of the GSEA rank metric, which may artificially boost scores. In the present example this effect has been ignored.