Here, we analyze differentially expressed genes. BCR::ABL1-negative myeloproliferative neoplasms (MPN) comprise a heterogeneous group of hematological neoplastic diseases. They all share a constitutive activation of the Janus kinases and signal transducer and activator of transcription (JAK/STAT) signaling pathway that is crucial for the initiation and progression of MPN. Therefore, targeted therapies with JAK inhibitors (JAKi) were developed over the last two decades. HEL and SET-2 are two of the most widely used human leukemia cell lines in research on myeloproliferative neoplasms (MPNs) and JAK2 V617F signaling. Both harbor the activating JAK2 V617F mutation alongside TP53 alterations, but they differ in lineage origin, JAK2 zygosity, and co-mutations.

We wanted to study the treatment of these two cell lines with JAKi for 14 days and 15 weeks and to identify differentially expressed genes compared to control.

For RNA sequencing (RNAseq), 2 μg of total RNA/sample was employed and strand specific 150 base paired-end RNAseq was performed using the Illumina NovaSeq platform by Genewiz (Leipzig, Germany). Approximately 20 million reads per sample were obtained. Reads were trimmed using Trimmomatic, quality checked with fastqc 0.11.9 and mapped to the human reference genome (hg38) employing the splice aware aligner STAR 2.7.9a. Quantifications on NCBI gene models (hg38refGene) were performed using featureCounts v2.0.0.

Bauer M, Vaxevanis C, Jaekel N, Hackl H, Wilfer A, Zoellig C, Haemmerle M, Müller-Tidow C, Al-Ali HK, Seliger B, Wickenhauser C. Association of the composition of the bone marrow tumor microenvironment in BCR::ABL1-negative myeloproliferative neoplasms with IFN-γ signaling and driver mutations. Leukemia. 2025. 39(10):2391-2405. doi: 10.1038/s41375-025-02706-3.

1. Load packages

Include all R and Bioconductor packages

# cran packages install.packages("conflicted")
library(conflicted)
library(tidyverse)
library(circlize)
library(scales)
library(ggnewscale)
library(msigdbr)
library(patchwork)
library(writexl)
library(grid)
if (!require("BiocManager", quietly = TRUE))
  install.packages("BiocManager")
# Bioconductor packages BiocManager::install("ComplexHeatmap")
library(DESeq2)
library(EnhancedVolcano)
library(ComplexHeatmap)
library(clusterProfiler)
library(ReactomePA)
library(org.Hs.eg.db)
library(enrichplot)
conflicts_prefer(dplyr::filter)
conflicts_prefer(dplyr::select)
conflicts_prefer(dplyr::rename)

2. Working directory and data resources

Set your preferred working directory and data resource

  di<-"L:/MO/" # set directory path
  setwd(di)  # set current directory 
  url <- "https://icbi.i-med.ac.at/teaching-material/mo/" # URL to access count data

3. Count data from RNAseq and sample information

From RNA sequencing experiment of HET and SET2 cell lines treated with JAKi for 14d and 15 weeks load count data and sample information

HEL <- read_tsv(paste0(url,"COUNT_MATRIX_GENE.txt"))
HEL_DF <- HEL |>
  select(c(1, 11:ncol(HEL))) |>   # columns 2-10 include annotation data
  column_to_rownames("SYMBOL") |>
  filter(rowSums(pick(everything())) > 100)  # or (\(x) x[rowSums(x) > 100, ])()
HEL_DF[1:10,1:5]
T <- read_tsv(paste0(url,"TARGET_HEL.txt"))  # T<-read.table("TARGET_HEL.txt", header=TRUE, sep="\t", check.names="FALSE")
sample_metadata <- T |>
  column_to_rownames("SAMPLE") |>
  mutate(CONDITION = factor(CONDITION))
sample_metadata[1:18,c(1,3:7)]

4. Fit DESeq2 model across all conditions and data normalization

Based on the count data (HEL_DF) and metadata (sample_metadata) using the factor variable CONDITION a DESeq2 model is fitted (DESeq2 Bioconductor package) across all 6 conditions

dds<-DESeqDataSetFromMatrix(countData = HEL_DF, colData = sample_metadata, design = ~ CONDITION)
dds_fit<-DESeq(dds)

Several normalization and transformation methods are available in DESeq2: - Size factor-normalized counts: Counts are normalized using estimated size factors to account for differences in sequencing depth and RNA composition between samples. Note that these counts are not normalized for gene length and are therefore intended for comparisons of the same gene across samples rather than comparisons between different genes. Unlike TPM (transcripts per million), DESeq2 normalization does not account for gene length. - Log2-transformed normalized counts: Size factor-normalized counts are log2-transformed after adding a pseudocount of 1 to avoid taking the logarithm of zero. - Regularized logarithm transformation (rlog): Reduces the dependence of variance on mean expression and shrinks differences between samples for lowly expressed genes. - Variance stabilizing transformation (VST): Reduces the dependence of variance on mean expression and is generally computationally faster than rlog, particularly for large datasets. The transformed expression values are suitable for exploratory data analysis, such as PCA, clustering, and heatmap visualization. Note that TPM values are not used here. Differential expression analysis with DESeq2 is performed using raw counts, with estimated size factors incorporated into the statistical model, rather than using TPM values or transformed normalized counts.

log2_norm_counts <- log2(counts(dds_fit, normalized = TRUE) + 1) |>
  as.data.frame() |>
  rownames_to_column("SYMBOL")
log2_norm_counts_anno <- HEL |>
  select(1:10) |>
  inner_join(log2_norm_counts, by = "SYMBOL")  # include annotation information from original data by matching SYMBOL
write_tsv(log2_norm_counts_anno,"HELSET_LOGNORM_1.tsv")

rlog1 <- assay(rlog(dds_fit)) |>
  as.data.frame() |>
  rownames_to_column("SYMBOL")
rlog1_anno <- HEL |>
  select(1:10) |>
  inner_join(rlog1, by = "SYMBOL")
write_tsv(rlog1_anno,"HELSET_RLOG.tsv")

vst1 <- assay(varianceStabilizingTransformation(dds_fit)) |>
  as.data.frame() |>
  rownames_to_column("SYMBOL")
vst1_anno <- HEL |>
  select(1:10) |>
  inner_join(vst1, by = "SYMBOL")
write_tsv(vst1_anno,"HELSET_VST.tsv")

5. Principal component analysis (PCA) on samples

To obtain an overview of the experiment, principal component analysis (PCA) is performed on the rlog-transformed expression data using the 500 most variable genes. This allows the visualization of overall sample similarities, group separation, potential batch effects, and outliers.

z<-plotPCA(rlog(dds_fit), intgroup=c("CONDITION")) # included in the DESeq2 package
z1<-z+theme_bw()+coord_fixed(xlim=c(-20,15),ylim = c(-12,12))+theme(aspect.ratio=1)+geom_point(aes(fill=group),size=4,pch=21,colour="black")
png("PCA500.png",width=5.5,height=5.5, units="in",res=600)
print(z1)
dev.off()
## png 
##   2

6. Differential expression analysis: HEL14D vs. HELCTRL

Define the contrast between HEL14D and HELCTRL and identify differentially expressed genes using DESeq2. Positive log2 fold changes indicate higher expression in HEL14D compared with HELCTRL, whereas negative log2 fold changes indicate lower expression.

res_14D_CTRL<-results(dds_fit, contrast=c("CONDITION","HEL_14D","HEL_CTRL"))

i11 <- T |>
  filter(CONDITION == "HEL_CTRL") |>
  pull(SAMPLE)
i12 <- T |>
  filter(CONDITION == "HEL_14D") |>
  pull(SAMPLE)
MEAN1 <- log2_norm_counts |>
  mutate(
    HEL_CTRL = rowMeans(pick(all_of(i11))),  # mean11<-as.numeric(apply(log2_norm_counts[,i11],1,mean))
    HEL_14D  = rowMeans(pick(all_of(i12)))
  ) |>
  select(SYMBOL, HEL_CTRL, HEL_14D)

DEG_HEL14D_HELCTRL <- HEL |>   # to add annotation and mean of log2(normalized_counts+1) for each condition
  select(1:9) |>
  inner_join(
    res_14D_CTRL |>
      as.data.frame() |>
      rownames_to_column("SYMBOL") |>
      left_join(MEAN1, by = "SYMBOL"), # match by SYMBOL
    by = "SYMBOL" 
  ) |>
  filter(baseMean>10)
# Export results
write_tsv(DEG_HEL14D_HELCTRL, "DEG_HEL14D_HELCTRL.txt")
write_xlsx(DEG_HEL14D_HELCTRL, "DEG_HEL14D_HELCTRL.xlsx")

To identify significantly differentially expressed genes, filter for genes with a baseMean (mean normalized count across all samples included in the DESeq2 analysis) > 10, an absolute log2 fold change > 1 (more than two-fold up- or downregulation), and an adjusted p-value (FDR) < 0.1

DEG_HEL14D_HELCTRL_SIG <- DEG_HEL14D_HELCTRL |>
  filter(
    baseMean>10,
    padj<0.1,
    abs(log2FoldChange)>1
  ) |>
  arrange(desc(log2FoldChange))
DEG_HEL14D_HELCTRL_SIG[1:10,]
write_tsv(DEG_HEL14D_HELCTRL_SIG, "DEG_HEL14D_HELCTRL_SIG.txt")
write_xlsx(DEG_HEL14D_HELCTRL_SIG, "DEG_HEL14D_HELCTRL_SIG.xlsx")

7. Volcano plot

Generate a volcano plot (log2 fold change versus −log10 p-value) using the EnhancedVolcano package and highlight significantly differentially expressed genes.

png("VOLCANO_HEL14D_HELCTRL.png", units="in", width=10, height=10, res=600,pointsize = 6)
DFR1<-data.frame(LOG2FC=DEG_HEL14D_HELCTRL$log2FoldChange, P=DEG_HEL14D_HELCTRL$pvalue, FDR=DEG_HEL14D_HELCTRL$padj)
row.names(DFR1)<-DEG_HEL14D_HELCTRL$SYMBOL
indh<-which((DFR1$P<10^-20 & DFR1$LOG2FC>2) | (DFR1$P<10^-20 & DFR1$LOG2FC< -2) | DFR1$LOG2FC>3.5 | DFR1$LOG2FC< -3.5 )
keyvals <- ifelse((DFR1$LOG2FC < -1 & DFR1$FDR<0.1) , 'royalblue',ifelse((DFR1$LOG2FC > 1 & DFR1$FDR<0.1), 'red','darkgray'))
names(keyvals)[keyvals == 'darkgray'] <- 'NS'
names(keyvals)[keyvals == 'red'] <- 'up (>2FC, FDR<0.1)'
names(keyvals)[keyvals == 'royalblue'] <- 'down (>2FC, FDR<0.1)'
lab_italics <- paste0("italic('", rownames(DFR1), "')")
selectLab_italics = paste0("italic('",rownames(DFR1)[indh],"')")
print(EnhancedVolcano(DFR1,selectLab = selectLab_italics, lab=lab_italics,   pCutoff = 0.05, title = 'HEL_14D versus HEL_CTRL',titleLabSize=25,
                      FCcutoff = 1.0, pointSize = 4.0,labSize = 6.0,labCol = 'black', labFace = 'bold', parseLabels = TRUE,
                      boxedLabels = TRUE,colAlpha = 4/5,legendPosition = 'top', legendLabSize = 20, legendIconSize = 4.0,
                      arrowheads = FALSE, colCustom = keyvals, drawConnectors = TRUE, subtitle = "Differential expression", subtitleLabSize=20, caption=paste("total: ",nrow(DEG_HEL14D_HELCTRL)," genes (mean>10)",sep=""),captionLabSize = 20,
                      widthConnectors = 0.5,colConnectors = 'black',x='LOG2FC',y='P',axisLabSize = 20))
dev.off()
## png 
##   2

8. Heatmap of DEGs with mor the 8-fold change

Generate a heatmap of significantly differentially expressed genes with an absolute log2 fold change > 3 (more than eight-fold up- or downregulation).

Prepare data for heatmap visualization individual samples z-score of rlog and final column with log2 fold-change

HEATMAP_Z <- DEG_HEL14D_HELCTRL |>
  filter(
    baseMean > 10,
    padj < 0.1,
    abs(log2FoldChange) > 3
  ) |>
  arrange(desc(log2FoldChange)) |>
  select(SYMBOL) |>
  left_join(
    rlog1 |> select(SYMBOL, all_of(c(i11, i12))),
    by = "SYMBOL"
  ) |>
  column_to_rownames("SYMBOL") |>
  as.matrix() |>
  t() |>
  scale() |>
  t()
HEATMAP_Z[1:10,]
##              HEL_CTRL_1 HEL_CTRL_2 HEL_CTRL_3 HEL_14D_1 HEL_14D_2 HEL_14D_3
## CYP26B1      -0.9612799 -0.9874032 -0.6633671 0.6981445 1.3704724 0.5434332
## MAPK4        -0.8877194 -1.0146108 -0.8149792 0.8194467 1.1004139 0.7974487
## HSPA6        -1.1660213 -0.7852060 -0.7557785 0.8402532 0.9794007 0.8873520
## PLCE1        -0.9221498 -0.9610139 -0.6795039 0.6658802 0.4374784 1.4593090
## APC2         -1.0247161 -1.0136227 -0.6517866 0.8519918 1.1220969 0.7160368
## LOC105371430 -1.0072695 -1.0135630 -0.6576920 0.5947402 1.0611954 1.0225888
## MPP7         -0.9060857 -0.8712406 -0.8633206 0.8503034 1.3128709 0.4774725
## HBA2         -1.1526558 -0.7865249 -0.7494609 0.8121406 1.1264938 0.7500072
## ESPN         -0.9676062 -0.9324757 -0.8278209 0.8628251 1.0448217 0.8202561
## HMOX1        -1.0406937 -0.9739906 -0.6954800 0.7968610 1.0547691 0.8585343
FC_FDR <- HEATMAP_Z |>
  as.data.frame() |>
  rownames_to_column("SYMBOL") |>
  select(SYMBOL) |>
  left_join(
    DEG_HEL14D_HELCTRL_SIG |>
      select(SYMBOL, log2FoldChange, padj),
    by = "SYMBOL"
  )   
FC_MAT <- FC_FDR |>
  select(SYMBOL, log2FoldChange) |>
  column_to_rownames("SYMBOL") |>
  rename(log2FC = log2FoldChange) |>
  as.matrix()
FC_MAT[1:10, 1, drop = FALSE]
##                log2FC
## CYP26B1      4.916744
## MAPK4        4.513819
## HSPA6        4.319875
## PLCE1        4.282035
## APC2         4.234155
## LOC105371430 4.193151
## MPP7         3.969412
## HBA2         3.839830
## ESPN         3.738198
## HMOX1        3.694739
significance <- case_when(
  FC_FDR$padj < 0.001 ~ "***",
  FC_FDR$padj < 0.01  ~ "**",
  FC_FDR$padj < 0.05  ~ "*",
  FC_FDR$padj < 0.1   ~ "°",
  TRUE               ~ ""
)
significance
##  [1] "***" "***" "***" "***" "***" "***" "***" "***" "***" "***" "***" "***"
## [13] "***" "**"  "***" "***" "***" "***" "***" "***" "***" "***" "***" "***"
## [25] "***" "***" "***" "***" "***" "**"  "***" "***" "***" "***" "***" "***"
## [37] "***" "*"   "***" "***" "***" "***" "***" "***"
lgd_FDR <- Legend(
  title = "FDR",
  labels = c("< 0.1", "< 0.05", "< 0.01", "< 0.001"),
  type = "points",
  pch = c("°", "*", "**", "***"),
  background = "transparent",
  legend_gp = gpar(col = "black", fontsize = 12, fontface = "bold")
)

Generate heatmap using package ComplexHeatmap

png("HEATMAP_8FC_HEL14D_HELCTRL.png", units="in", width=7, height=11, res=600,pointsize = 6)
ht1 <- Heatmap(
  HEATMAP_Z,
  name = "z-score",
  col = colorRamp2(c(-1, 0, 1), c("royalblue", "white", "red")),
  rect_gp = gpar(col = "white", lwd = 1),
  column_split = c(rep("HEL_CTRL", length(i11)),rep("HEL_14D", length(i12))),
  row_split = factor(ifelse(as.vector(FC_MAT[,1]) > 0, "UP", "DOWN"),levels = c("UP", "DOWN")),
  heatmap_legend_param = list(title = "z-score",at = seq(-1, 1, by = 0.5)),
  width = unit(80, "mm"),
  height = unit(nrow(HEATMAP_Z) * 5 + 3, "mm"),
  column_names_rot = 45,
  cluster_rows = FALSE,
  cluster_columns = FALSE,
  show_row_names = FALSE,
  row_gap = unit(3, "mm"),
  column_gap = unit(3, "mm")
)

ht2 <- Heatmap(
  FC_MAT,
  name = "log2FC",
  col = colorRamp2(c(-4, 0, 4), c("royalblue", "white", "red")),
  rect_gp = gpar(col = "white", lwd = 1),
  heatmap_legend_param = list(title = "log2FC",at = seq(-4, 4, by = 2)),
  cluster_rows = FALSE,
  cluster_columns = FALSE,
  show_row_names = TRUE,
  row_names_side = "right",
  row_names_gp = gpar(fontface = "italic", fontsize = 12),
  column_names_rot = 45,
  width = unit(10, "mm"),
  height = unit(nrow(HEATMAP_Z) * 5 + 3, "mm"),
  cell_fun = function(j, i, x, y, width, height, fill) {
    grid.text(significance[i], x, y,gp = gpar(fontsize = 12, col = "white",fontface = "bold"))
  }
)

draw(ht1 + ht2,heatmap_legend_list = list(lgd_FDR))
dev.off()
## png 
##   2

9. Functional annotation (GO, Reactome) using gene set enrichment analysis (GSEA)

Gene Set Enrichment Analysis (GSEA) using the clusterProfiler package and Gene Ontology Biological Process (GO BP) gene sets. Rank gene symbols by the Wald statistic (log2 fold change divided by its standard error) obtained from DESeq2 analysis, or alternatively by log2 fold change alone.

gene_list_symbol <- DEG_HEL14D_HELCTRL |>
  filter(is.finite(stat), !is.na(SYMBOL)) |>
  arrange(desc(stat)) |>
  select(SYMBOL, stat) |>
  deframe()
gsea_gobp <- gseGO(geneList     = gene_list_symbol,
                   OrgDb        = org.Hs.eg.db,
                   ont          = "BP",
                   keyType = "SYMBOL",
                   minGSSize    = 10,
                   eps=0,
                   pAdjustMethod = "BH",
                   maxGSSize    = 500,
                   pvalueCutoff = 0.1,
                   verbose      = FALSE,
)
gsea_gobp_df<-gsea_gobp |>
  as.data.frame()
write_tsv(gsea_gobp_df,"GOBP_GSEA_HEL14D_HELCTRL.tsv")
write_xlsx(gsea_gobp_df,"GOBP_GSEA_HEL14D_HELCTRL.xlsx")

Dot plot showing the top 10 positively and top 10 negatively enriched biological processes. The gene ratio represents the proportion of core enrichment (leading-edge) genes relative to all genes in the respective gene set represented in the ranked gene list.

png("GOBP_DOTPLOT_HEL14D_HELCTRL.png", units="in", width=10, height=10, res=600,pointsize = 6)
print(dotplot(gsea_gobp, showCategory = 10, title = "Gene Ontology [Biological Process]" , split=".sign") + facet_grid(.~.sign))
dev.off()
## png 
##   2

Pairwise similarities between enriched biological processes using the pairwise_termsim() function from the enrichplot package. By default, similarity is calculated using the Jaccard coefficient based on shared genes between gene sets (core enrichment genes for GSEA). The resulting similarity matrix can be used to visualize relationships between enriched biological processes and identify clusters of related terms using an enrichment map.

XG1 = pairwise_termsim(gsea_gobp)
png("GOBP_ENRPLOT_HEL14D_HELCTRL.png", units="in", width=10, height=10, res=600,pointsize = 6)
print(emapplot(XG1, showCategory = 20))
dev.off()
## png 
##   2

Gene Set Enrichment Analysis (GSEA) using the gsePathway() function from the ReactomePA package on a ranked list of Entrez gene IDs based on the Wald statistic from DESeq2 analysis to identify positively and negatively enriched Reactome pathways.

gene_list <- DEG_HEL14D_HELCTRL |>
  filter(is.finite(stat), !is.na(SYMBOL)) |>
  mutate(
    ENTREZID = unname(AnnotationDbi::mapIds(
      org.Hs.eg.db,
      keys = SYMBOL,
      column = "ENTREZID",
      keytype = "SYMBOL",
      multiVals = "first"
    ))
  ) |>
  filter(!is.na(ENTREZID)) |>
  arrange(desc(abs(stat))) |>   # sort to keep the most abs stat if more than 1 
  distinct(ENTREZID, .keep_all = TRUE) |>  #Removes rows with duplicated ENTREZID only first
  arrange(desc(stat)) |>
  select(ENTREZID, stat) |>
  deframe() #get a named vector
gene_list[1:5]
##     5596   200942     3162     2495    64097 
## 19.56912 17.90105 17.89281 15.34874 14.82847
gsea_reactome<-gsePathway(
  gene_list,
  organism = "human",
  exponent = 1,
  minGSSize = 10,
  maxGSSize = 500,
  eps = 0,
  pvalueCutoff = 0.2,
  pAdjustMethod = "BH",
  verbose = TRUE,
  seed = FALSE,
  by = "fgsea",
)
gsea_reactome_readable <- setReadable(gsea_reactome, OrgDb = org.Hs.eg.db, keyType="ENTREZID")
gsea_reactome_df<-as.data.frame(gsea_reactome_readable)
write_tsv(gsea_reactome_df,"REACTOME_GSEA_HEL14D_HELCTRL.tsv")
write_xlsx(gsea_reactome_df,"REACTOME_GSEA_HEL14D_HELCTRL.xlsx")

Dot plot showing the top 10 positively and top 10 negatively enriched Reactome Pathways. The gene ratio represents the proportion of core enrichment (leading-edge) genes relative to all genes in the respective gene set represented in the ranked gene list.

png("REACTOME_DOTPLOT_HEL14D_HELCTRL.png", units="in", width=10, height=10, res=600, pointsize = 6)
print(dotplot(gsea_reactome_readable, showCategory = 10, title = "Enriched Pathways" , split=".sign") + facet_grid(.~.sign))
dev.off()
## png 
##   2

Pairwise similarities between enriched Reactome pathways using the pairwise_termsim() function from the enrichplot package. By default, similarity is calculated using the Jaccard coefficient based on shared genes between gene sets (core enrichment genes for GSEA). The resulting similarity matrix can be used to visualize relationships between enriched biological processes and identify clusters of related terms using an enrichment map.

x1 = pairwise_termsim(gsea_reactome)
png("REACTOME_ENRPLOT_HEL14D_HELCTRL.png", units="in", width=10, height=10, res=600,pointsize = 6)
print(emapplot(x1, showCategory = 20))
dev.off()
## png 
##   2

10. Functional annotation (GO) using over representation analysis (ORA)

Over representation analysis (ORA) using the clusterProfiler package and Gene Ontology Biological Process (GO BP) gene sets and a list of signifcantly upregulated genes in HEL14D vs HELCTRL.

gene_universe <- DEG_HEL14D_HELCTRL |>
    select(SYMBOL) |>
    deframe()

genes_up <- DEG_HEL14D_HELCTRL |>
  filter(log2FoldChange>1,padj<0.1,baseMean>10) |>
  select(SYMBOL) |>
  deframe()

ora_gobp_up <- enrichGO(
  gene = genes_up,
  universe = gene_universe,   
  OrgDb = org.Hs.eg.db,
  keyType = "SYMBOL",
  ont = "BP",
  pAdjustMethod = "BH",
  pvalueCutoff = 0.05,
  qvalueCutoff = 0.2,
  readable = TRUE
)
ora_gobp_up_df<-ora_gobp_up |>
  as.data.frame()

write_tsv(ora_gobp_up_df,"GOBP_ORA_UP_HEL14D_HELCTRL.tsv")
write_xlsx(ora_gobp_up_df,"GOBP_ORA_UP_HEL14D_HELCTRL.xlsx")

11. GSEA of gene sets from MSigDB and custom gene sets

Gene Set Enrichment Analysis (GSEA) using the GSEA() function from the clusterProfiler package on a ranked list of gene symbols and predefined gene sets from MSigDB (Molecular Signatures Database) or custom gene sets provided in GMT format.

Two selected signature retrieved from MSigDB using the package msigdbr

MSIG <- msigdbr(
  species = "Homo sapiens",
  collection = "H"
) |>
  filter(gs_name %in% c(
    "HALLMARK_INTERFERON_GAMMA_RESPONSE",
    "HALLMARK_HYPOXIA"
  )) |>
  dplyr::select(gs_name, gene_symbol) |>
  distinct()

gsea_msig <- GSEA(
  geneList = gene_list_symbol,
  TERM2GENE = MSIG,
  minGSSize = 10,
  maxGSSize = 500,
  pvalueCutoff = 1,
  pAdjustMethod = "BH",
  eps = 0,
  verbose = TRUE
)
gsea_msig_df<- gsea_msig |>
  as.data.frame()
print(gsea_msig_df[, c(2, 3, 4, 5, 6, 7)],row.names = FALSE)
##                         Description setSize enrichmentScore      NES
##                    HALLMARK_HYPOXIA     147       0.4245635 1.913870
##  HALLMARK_INTERFERON_GAMMA_RESPONSE     158       0.2280688 1.034331
##        pvalue     p.adjust
##  2.016463e-06 4.032926e-06
##  3.539192e-01 3.539192e-01
write_tsv(gsea_msig_df,"MSIG_GSEA_HEL14D_HELCTRL.tsv")
write_xlsx(gsea_msig_df,"MSIG_GSEA_HEL14D_HELCTRL.xlsx")

Custom gene sets provided in GMT format, including the 50 Hallmark gene sets originally obtained from MSigDB and additional gene sets of interest.

custom_gmt <- read.gmt(paste0(url,"GENESETS.gmt"))
set.seed(42) # Since GSEA involves random sampling set a random seed to ensure reproducibility of the results.
gsea_custom <- GSEA(
  geneList      = gene_list_symbol,
  TERM2GENE     = custom_gmt,
  minGSSize     = 10,
  maxGSSize     = 500,
  pvalueCutoff  = 1,
  pAdjustMethod = "BH",
  eps = 0,
  verbose       = FALSE
)
gsea_custom_df<- gsea_custom |>
  as.data.frame()
write_tsv(gsea_custom_df,"CUSTOM_GSEA_HEL14D_HELCTRL.tsv")
write_xlsx(gsea_custom_df,"CUSTOM_GSEA_HEL14D_HELCTRL.xlsx")

Bar diagram based on normalized enrichment score (NES) and adjusted p-value (FDR) for significant hallmark sets (custom sets) with abs(NES)>1.5.

gsea_custom_sel<- gsea_custom_df |>
  filter(abs(NES)>1.5,p.adjust<0.1) |>
  mutate(Description = Description |>
           str_remove("^HALLMARK_") |>
           str_replace_all("_", " ") |>
           str_to_sentence() |>
           str_replace_all("Dna", "DNA") |>
           str_replace_all("Myc", "MYC") |>
           str_replace_all("Tnfa", "TNFA") |>
           str_replace_all("nfkb", "NFKB") |>
           str_replace_all("E2f", "E2F") |>  
           str_replace_all("G2m", "G2M")) |>  
  select(Description,NES,p.adjust) |>
  rename(FDR = p.adjust) |>
  arrange(desc(NES)) |>
  mutate(signed_log10FDR = -log10(FDR) * sign(NES))

gsp<-ggplot(gsea_custom_sel,
            aes(x = reorder(Description, NES),
                y = NES,
                fill = signed_log10FDR)) +
  geom_col(width = 0.8) +
  coord_flip() +
  scale_fill_gradient2(
    low = "royalblue",
    mid = "grey90",
    high = "red",
    midpoint = 0,
    limits = c(-5, 5),
    oob = scales::squish,
    breaks = c(-5, -2.5, 0, 2.5, 5),
    name = expression(signed~-log[10](FDR))
  ) +
  labs(x = NULL, y = "NES") +
  theme_bw() +
  theme(
    legend.position = "right",
    axis.text.y = element_text(size = 14, colour = "black"),
    axis.text.x = element_text(size = 14,colour = "black"),
    axis.title = element_text(size = 14,colour = "black")
  ) +
  theme(
    legend.title = element_text(size = 14, colour = "black"),
    legend.text = element_text(size = 14, colour = "black")
  )
ggsave(
  filename = "HALLMARKS_BAR_PLOT.png",
  plot = gsp,
  width = 9,
  height = 4,
  units = "in",
  dpi = 600
)

Enrichment plot for the most significant hallmark gene set (similar to that of original GSEA software)

sname<-"HALLMARK_HEME_METABOLISM"
  gid <- gsea_custom@result$ID[gsea_custom@result$Description == sname]
  cust <- gseaplot2(    
    gsea_custom,
    geneSetID = gid[1],
    title = sname,
    color = "green"
  )
  cust2 <- cust[[2]]
  rect_layer <- which(sapply(cust2$layers, function(x)
    inherits(x$geom, "GeomRect")
  ))
  # remove original coarse color bar
  old_bar <- cust2$layers[[rect_layer]]$data
  cust2$layers <- cust2$layers[-rect_layer]
  # make fine-grained bar: one tile per gene/rank
  bar_df <- data.frame(
    x = seq_along(gene_list_symbol),
    metric = gene_list_symbol
  )
  lim <- quantile(abs(bar_df$metric), 0.99, na.rm = TRUE)
  bar_df$col_new <- col_numeric(
    palette = c("darkblue", "royalblue", "white", "red", "darkred"),
    domain = c(-lim, lim)
  )(
    pmax(pmin(bar_df$metric, lim), -lim)
  )
  # use the same y-position as original bar
  bar_df$ymin <- old_bar$ymin[1]
  bar_df$ymax <- old_bar$ymax[1]
  cust2_new <- cust2 +
    geom_rect(
      data = bar_df,
      aes(
        xmin = x - 0.5,
        xmax = x + 0.5,
        ymin = ymin,
        ymax = ymax,
        fill = I(col_new)
      ),
      alpha=0.85,
      inherit.aes = FALSE
    )
  final_plot<-plot_list(
    cust[[1]],      # enrichment score
    cust2_new,    # your new color bar
    cust[[3]],      # gene hits
    ncol = 1,
    heights = c(0.55, 0.14, 0.26)
  ) 
  final_plot <- wrap_elements(final_plot) +
    theme(
      plot.margin = margin(10, 10, 10, 10)
    )
  ggsave(
    filename = paste0(sname, "_enrichment_plot.png"),
    plot = final_plot,
    width = 5,
    height = 5,
    units = "in",
    dpi = 300,
    device = "png"
  )

Generate heatmap for leading edge genes (core enrichment genes) using ComplexHeatmap

leading_edge_genes <- str_split(gsea_custom@result$core_enrichment, "/")
names(leading_edge_genes) <- make.names(gsea_custom@result$Description)
leading_edge_genes[[sname]] 
##  [1] "ALAD"     "DMTN"     "ENDOD1"   "HBZ"      "EPOR"     "SELENBP1"
##  [7] "RBM38"    "ADIPOR1"  "TRIM58"   "TAL1"     "BLVRB"    "ARHGEF12"
## [13] "OPTN"     "TFDP2"    "ACKR1"    "TNS1"     "YPEL5"    "SMOX"    
## [19] "AGPAT4"   "KLF3"     "HBB"      "ALAS2"    "TMCC2"    "MPP1"    
## [25] "EPB42"    "SEC14L1"  "NUDT4"    "CCND3"    "HBQ1"     "SLC25A37"
## [31] "GATA1"    "NCOA4"    "SLC10A3"  "SLC25A38" "SPTA1"    "H1-0"    
## [37] "KEL"      "BTG2"     "FOXJ2"    "PPOX"     "ICAM4"    "NEK7"    
## [43] "FOXO3"    "DAAM1"    "LRP10"    "PPP2R5B"  "C3"       "OSBP2"   
## [49] "RIOK3"    "EIF2AK1"  "FBXO7"    "EZH1"     "FN3K"     "ATP6V0A1"
## [55] "CIR1"     "KDM7A"    "MYL4"     "RBM5"     "ABCB6"    "GYPC"    
## [61] "KHNYN"    "CLCN3"    "RNF19A"   "SLC2A1"   "MARCHF2"  "BACH1"   
## [67] "NFE2"     "KLF1"     "CLIC2"    "CAT"      "TCEA1"    "MKRN1"   
## [73] "HEBP1"    "ARL2BP"   "SNCA"     "GAPVD1"   "TMEM9B"   "UCP2"    
## [79] "SLC30A10" "MARCHF8"  "CCDC28A"  "ERMAP"    "MXI1"     "TFRC"    
## [85] "SYNJ1"    "NARF"     "SDCBP"    "LPIN2"    "BPGM"     "CPOX"    
## [91] "CTSB"     "GCLC"     "XK"       "BNIP3L"   "ANK1"

12. Differential expression analysis: SET15W vs. SETCTRL

Perform differential expression analysis for comparison between SET15W and SETCTRL samples for protein coding genes only.