4  scRNA: Pseudobulk Differential Expression (Muscat Workflow)

4.1 Environment Setup

library(Seurat)
library(SingleCellExperiment)
library(scuttle)
library(limma)
library(tidyverse)
library(muscat)
library(princurve)
library(ggplot2)
library(msigdbr)
library(fgsea)
library(GSEAtraining)  
library(EnhancedVolcano)

4.2 Loading in an Intergrated Object

# Replace the path with working directory 
merged <- readRDS("/jsimonlab/users/bshim/Shuntaro_scRNA_TCR/analysis_052124/gated_altered_threshold_1_integrated.rds")

4.3 Sample-level Analysis: Pseudobulk Methods with Muscat

merged[['RNA']] <- JoinLayers(merged[['RNA']])
DefaultAssay(merged) <- "RNA"
dim(merged)
[1] 61578 68740
# Using Raw Counts 
merged.sce <- as.SingleCellExperiment(merged,assay="RNA")
  
# Compute log2 CPM consistent
merged.sce <- computeLibraryFactors(merged.sce)
merged.sce <- logNormCounts(merged.sce)
  
(mergedCondition.sce <- prepSCE(merged.sce,
    kid = "RNA_snn_res.0.3",
    gid = "Condition",
    sid = "Sample",
    drop=T))
class: SingleCellExperiment 
dim: 61578 68740 
metadata(1): experiment_info
assays(2): counts logcounts
rownames(61578): 5-8S-rRNA 5S-rRNA ... ZZEF1 ZZZ3
rowData names(0):
colnames(68740): Pool142_1_R_TTGGCAAGTCGGGTCT
  Pool142_1_R_AAGCCGCGTCCCTTGT ... Pool144_3_NR_AACTCTTTCGCATGGC
  Pool144_3_NR_CCCATACGTACGACCC
colData names(3): cluster_id sample_id group_id
reducedDimNames(4): PCA UMAP.UNINTEGRATED INTEGRATED.HARMONY
  UMAP.HARMONY
mainExpName: RNA
altExpNames(0):
pb <- aggregateData(mergedCondition.sce,
    assay = "counts",fun="sum",
    by = c("cluster_id", "sample_id"))


# one sheet per subpopulation
assayNames(pb)
[1] "0" "1" "2" "3" "4" "5"
# pseudobulks for 1st subpopulation
t(head(assay(pb)))
             5-8S-rRNA 5S-rRNA       7SK     A1BG A1BG-AS1       A1CF
Pool142_1_R          0       0  384.9131  97.8000     24.0 0.00000000
Pool142_2_NR         0       0  616.2380 174.1250     57.5 0.00000000
Pool142_3_NR         0       0  485.1923  81.2250     37.0 0.00000000
Pool142_4_NR         0       0  377.6047 102.7000     44.0 0.00000000
Pool142_5_R          0       0 1445.6681 299.9457    105.5 0.00000000
Pool142_6_R          0       0 1491.8766 247.2000     69.0 0.01012797
Pool142_7_NR         0       0 2347.5901 226.9000     56.0 0.00000000
Pool144_1_R          0       0  491.6196 252.0000     61.5 0.00000000
Pool144_2_NR         0       0  614.5267 219.9000     68.0 0.00000000
Pool144_3_NR         0       0  136.0976  22.0000      6.0 0.00000000

4.4 Constructing Design Matrix and Running DESeq based Pseudobulk Differential Expression

set.seed(61217)
ei <- metadata(mergedCondition.sce)$experiment_info
# Meta Data 
batch = factor(c("A", "A", "A", "A", "A", "A", "A", "B", "B", "B"))
Sex = factor(c("Male", "Female", "Female", "Male", "Male", "Male", "Female", "Female", "Female", "Female"))
mm <- model.matrix(~0 + ei$group_id + Sex)
dim_name <- levels(ei$group_id)
dim_name[3] <- "Sex"
dimnames(mm) <- list(ei$sample_id, dim_name)
contrast <- makeContrasts("R-NR", levels = mm)
res <- pbDS(pb, design = mm, contrast = contrast, method="DESeq2", min_cells = 50)

  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |======================================================================| 100%
tbl_all <- res$table[[1]]

sort_for_sig <- function(u) {
  u <- dplyr::filter(u, p_adj.loc < 0.05, abs(logFC) > 1)
  dplyr::arrange(u, p_adj.loc)
}
# filter FDR < 5%, abs(logFC) > 1 & sort by adj. p-value
tbl_fil_all <- lapply(tbl_all, sort_for_sig)

# nb. of DS genes & % of total by cluster
n_de <- vapply(tbl_fil_all, nrow, numeric(1))
p_de <- format(n_de / nrow(mergedCondition.sce) * 100, digits = 3)
data.frame("#DS" = n_de, "%DS" = p_de, check.names = FALSE)
  #DS     %DS
0   2 0.00325
1  14 0.02274
2   3 0.00487
3   1 0.00162
4  70 0.11368
5  34 0.05521
# view top 2 hits in each cluster
top2 <- bind_rows(lapply(tbl_fil_all
                         
                         , top_n, 2, p_adj.loc))
format(top2[, -ncol(top2)], digits = 2)
              gene cluster_id baseMean logFC lfcSE stat   p_val p_adj.loc
1            ERAP2          0      811  -1.7  0.35 -4.7 2.5e-06   0.01449
2  ENSG00000253853          0       36   2.8  0.63  4.5 6.3e-06   0.02180
3         TRBV10-3          1      320   1.3  0.32  4.1 3.4e-05   0.02368
4          SLC27A2          1       34  -1.7  0.43 -4.0 6.5e-05   0.04132
5            ERAP2          2      362  -1.7  0.31 -5.5 4.5e-08   0.00031
6           IFNGR2          2      481  -1.0  0.21 -4.8 1.9e-06   0.00579
7          SULT1A1          3       21   2.8  0.65  4.4 1.2e-05   0.03768
8          CCDC167          4       76  -1.3  0.42 -3.0 2.4e-03   0.04728
9            ROMO1          4      113  -1.3  0.42 -3.0 2.6e-03   0.04912
10            RRM2          5      609  -1.3  0.36 -3.5 3.9e-04   0.04320
11        RPL13P12          5       49 -20.9  5.95 -3.5 4.4e-04   0.04745
   p_adj.glb
1    0.00567
2    0.01004
3    0.02850
4    0.04392
5    0.00028
6    0.00448
7    0.01568
8    0.28105
9    0.29274
10   0.11146
11   0.11766

4.5 Running Paired Pseudobulk Experiment

# List of all possible 2 Male and 2 Female Pairs 
sample_pairs <- list(
  c("Pool144_1_R", "Pool142_1_R", "Pool142_4_NR", "Pool142_2_NR"),
  c("Pool144_1_R", "Pool142_5_R", "Pool142_4_NR", "Pool142_2_NR"),
  c("Pool144_1_R", "Pool142_6_R", "Pool142_4_NR", "Pool142_2_NR"),
  c("Pool144_1_R", "Pool142_1_R", "Pool142_4_NR", "Pool142_3_NR"),
  c("Pool144_1_R", "Pool142_5_R", "Pool142_4_NR", "Pool142_3_NR"),
  c("Pool144_1_R", "Pool142_6_R", "Pool142_4_NR", "Pool142_3_NR"),
  c("Pool144_1_R", "Pool142_1_R", "Pool142_4_NR", "Pool142_7_NR"),
  c("Pool144_1_R", "Pool142_5_R", "Pool142_4_NR", "Pool142_7_NR"),
  c("Pool144_1_R", "Pool142_6_R", "Pool142_4_NR", "Pool142_7_NR"),
  c("Pool144_1_R", "Pool142_1_R", "Pool142_4_NR", "Pool144_2_NR"),
  c("Pool144_1_R", "Pool142_5_R", "Pool142_4_NR", "Pool144_2_NR"),
  c("Pool144_1_R", "Pool142_6_R", "Pool142_4_NR", "Pool144_2_NR")
)

cluster_1_gene <- list()
cluster_4_gene <- list()
cluster_2_gene <- list()
cluster_3_gene <- list()
cluster_5_gene <- list()
cluster_0_gene <- list()
i=1 

cluster_1_all <- list()
cluster_4_all <- list()
cluster_2_all <- list()
cluster_3_all <- list()
cluster_5_all <- list()
cluster_0_all <- list()

for (pair in sample_pairs) {
  # subset only pair samples
  subset_df <- subset(merged, Sample %in% pair)
  subset_df[['RNA']] <- JoinLayers(subset_df[['RNA']])
  merged.sce <- as.SingleCellExperiment(subset_df,assay="RNA")
  
  # Compute log2 CPM consistent
  merged.sce <- computeLibraryFactors(merged.sce)
  merged.sce <- logNormCounts(merged.sce)
  
  (mergedCondition.sce <- prepSCE(merged.sce,
    kid = "RNA_snn_res.0.3",
    gid = "Condition",
    sid = "Sample",
    drop=T))
  
  pb <- aggregateData(mergedCondition.sce,
      assay = "counts",fun="sum",
      by = c("cluster_id", "sample_id"))
  
  ei <- metadata(mergedCondition.sce)$experiment_info
  mm <- model.matrix(~0 + ei$group_id)
  
  dim_name <- levels(ei$group_id)
  dimnames(mm) <- list(ei$sample_id, dim_name)
  contrast <- makeContrasts("R-NR", levels = mm)
  res <- pbDS(pb, design = mm, contrast = contrast, method="DESeq2", min_cells = 50)
  # access results table for 1st comparison
  tbl <- res$table[[1]]
  # one data.frame per cluster
  names(tbl)
  tbl_fil <- lapply(tbl, function(u) {
    u <- dplyr::filter(u, p_adj.loc < 0.05)
    dplyr::arrange(u, p_adj.loc)
  })
  
  # Getting the statistically significant genes
  cluster_1_gene[[i]] <- tbl_fil$'1'
  cluster_4_gene[[i]] <- tbl_fil$'4'
  cluster_2_gene[[i]] <- tbl_fil$'2'
  cluster_3_gene[[i]] <- tbl_fil$'3'
  cluster_5_gene[[i]] <- tbl_fil$'5'
  cluster_0_gene[[i]] <- tbl_fil$'0'
  i = i + 1
  
  # outputting DE object with all genes
  cluster_1_all[[i]] <- tbl$'1'
  cluster_4_all[[i]] <- tbl$'4'
  cluster_2_all[[i]] <- tbl$'2'
  cluster_3_all[[i]] <- tbl$'3'
  cluster_5_all[[i]] <- tbl$'5'
  cluster_0_all[[i]] <- tbl$'0'
  
}

  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |======================================================================| 100%


  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |======================================================================| 100%


  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |======================================================================| 100%


  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |======================================================================| 100%


  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |======================================================================| 100%


  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |======================================================================| 100%


  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |======================================================================| 100%


  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |======================================================================| 100%


  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |======================================================================| 100%


  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |======================================================================| 100%


  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |======================================================================| 100%


  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |======================================================================| 100%

4.6 Function to Combine DE Objects of each Paired Analysis

# Paired analysis 
# If Found in more than 2 significant pairs, i would consider that as significant
# In this case, I will take lowest logFC and highest padj


generate_de_objects <- function(x) {
  # bind rows of DE objects from each pairs
  temp_0_all <- bind_rows(x)
  temp_0_all <- temp_0_all %>%
    filter(!is.na(p_adj.loc)) %>%
    group_by(gene) %>%
    summarize(
      logFC = if (sum(p_adj.loc < 0.05) >= 2) {  # Check if there are 2 or more items with p_adj.loc < 0.05
        # Get the index of the logFC with the minimum absolute value where p_adj.loc < 0.05
        min_logFC_index <- which.min(abs(logFC[p_adj.loc < 0.05]))
        logFC[p_adj.loc < 0.05][min_logFC_index]
      } else {
        # Get the minimum of logFC overall 
        sorted_logFC <- sort(logFC, na.last = TRUE)  # Sort logFC values, ignoring NA
        sorted_logFC[1]
      },
      # case of more than 2 
      p_adj.loc = if (sum(p_adj.loc < 0.05) >= 2) {  # Check if there are 2 or more items with p_adj.loc < 0.05
        max(p_adj.loc[p_adj.loc < 0.05], na.rm = TRUE)  # Take the maximum p_adj.loc where p_adj.loc < 0.05
      } else {
        # Get the maximum of p_adj.loc overall
        sorted_p_adj <- sort(p_adj.loc, decreasing = TRUE, na.last = TRUE)  # Sort p_adj.loc values in descending order, ignoring NA
        if (sorted_p_adj[1] < 0.05) {
          # if the largest pvalue is not significant,
          sorted_p_adj[1] = 1
        }
        sorted_p_adj[1]  # Select the largest value
      }
    ) %>%
    ungroup()
  temp_0_all <- drop_na(temp_0_all)
  temp_0_all <- temp_0_all %>%
    mutate(across(everything(), ~ ifelse(is.infinite(.), 1, .)))
  return(temp_0_all)
}

4.7 Function to Combine DE Objects of Sample-Level / Pairwise Analysis

# We are combining the DE object from the paired and the conventional DE analysis with sex as covariate. 
# We consider the conventional DE analysis as a priority over the paired analysis 
# Within the paired DE object, if there is a padj and logFC from the conventional analysis, replace the logFC and padj with it 


update_tbl <- function(x,num) {
  temp <- tbl[[num]]
  updated_tbl <- temp %>%
  left_join(x %>% select(gene, logFC, p_adj.loc), by = "gene", suffix = c("", ".new")) %>%
  mutate(
    logFC = ifelse(!is.na(logFC.new), logFC.new, logFC),  # Replace logFC if there's a match
    p_adj.loc = ifelse(!is.na(p_adj.loc.new), p_adj.loc.new, p_adj.loc)  # Replace p_adj.loc if there's a match
  ) %>%
  select(-logFC.new, -p_adj.loc.new) 
}

4.8 Generating Final DE Objects

vis_c0 <- generate_de_objects(cluster_0_all)
vis_c0_sig <- vis_c0[vis_c0$p_adj.loc<0.05,]
vis_c1 <- generate_de_objects(cluster_1_all)
vis_c1_sig <- vis_c1[vis_c1$p_adj.loc<0.05,]
vis_c2 <- generate_de_objects(cluster_2_all)
vis_c2_sig <- vis_c2[vis_c2$p_adj.loc<0.05,]
vis_c3 <- generate_de_objects(cluster_3_all)
vis_c3_sig <- vis_c3[vis_c3$p_adj.loc<0.05,]
vis_c4 <- generate_de_objects(cluster_4_all)
vis_c4_sig <- vis_c4[vis_c4$p_adj.loc<0.05,]
# Conducted on pseudobulk de on all samples

# Lacking statistically significant outputs from the paired analysis but only in the conventional DE analysis
vis_c5 <- tbl_all$"5"
vis_c5 <- vis_c5 %>% filter(!is.na(p_adj.loc)) %>% select(gene,p_adj.loc, logFC)


vis_c0_up <- update_tbl(vis_c0_sig, 1)
vis_c0_up <- vis_c0_up %>% filter(!is.na(p_adj.loc)) %>% select(gene,p_adj.loc, logFC)
vis_c1_up <- update_tbl(vis_c1_sig, 2)
vis_c1_up <- vis_c1_up %>% filter(!is.na(p_adj.loc)) %>% select(gene,p_adj.loc, logFC)
vis_c2_up <- update_tbl(vis_c2_sig, 3)
vis_c2_up <- vis_c2_up %>% filter(!is.na(p_adj.loc)) %>% select(gene,p_adj.loc, logFC)
vis_c3_up <- update_tbl(vis_c3_sig, 4)
vis_c3_up <- vis_c3_up %>% filter(!is.na(p_adj.loc)) %>% select(gene,p_adj.loc, logFC)
vis_c4_up <- update_tbl(vis_c4_sig, 5)
vis_c4_up <- vis_c4_up %>% filter(!is.na(p_adj.loc)) %>% select(gene,p_adj.loc, logFC)

4.9 Plotting Volcano Plots

plot_volcano <- function(x, num, subtitle, gene_list) {
  x <- na.omit(x)
  x$gene <- gsub("-", "_", x$gene)
  title <- paste("Cluster", num, sep="")
  temp <- x[x$gene %in% gene_list,]
  gene_list <- c(temp[(temp$p_adj.loc < 0.05 & abs(temp$logFC) > 0.5),]$gene)
  
  # Add gene_names to top genes 
  # top 5 by highest logFC
  top_logFC <- x[order(-abs(x$logFC)), ][1:8, "gene"]
  # top 5 by lowest adjusted p-value
  top_padj <- x[order(x$p_adj.loc), ][1:8, "gene"]
  # combine & ensure uniqueness
  highlight_genes <- unique(c(gene_list, top_logFC, top_padj))
  
  
  p1 <- EnhancedVolcano(x,
  x = 'logFC',
  y = 'p_adj.loc',
  lab = x$gene,
  selectLab = highlight_genes,
  xlab = bquote(~Log[2]~ 'fold change'),
  pCutoff = 0.05,
  pointSize = 6.0,
  labSize = 8.0,
  title = title,
  subtitle = subtitle,
  FCcutoff = 0,
  labCol = 'black',
  labFace = 'italic',
  col = c('black', 'pink', 'purple', 'red3'),
  colAlpha = 4/5,
  legendPosition = 'bottom',
  legendLabSize = 14,
  legendIconSize = 4.0,
  drawConnectors = TRUE,
  colConnectors = "black",
  widthConnectors = 1.0,
  arrowheads = FALSE, boxedLabels = TRUE, 
  box.padding=1.0,
  titleLabSize = 24,
  subtitleLabSize = 20,
  axisLabSize = 18)
  p1 + theme(
    plot.title = element_text(size = 24, face = "bold"),
    plot.subtitle = element_text(size = 20, face = "italic"),
    axis.title = element_text(size = 18, face = "bold")
  )
  return(p1) 
  
}

4.10 Generating Volcano Plots For Each Cluster

all_vis <- bind_rows(
  c0 = vis_c0_up,
  c1 = vis_c1_up,
  c2 = vis_c2_up,
  c3 = vis_c3_up,
  c4 = vis_c4_up,
  c5 = vis_c5,
  .id = "cluster"
)

#subset all_vis to vis_c0 to 5 _up
vis_c0_up <- all_vis[all_vis$cluster == "c0",]
vis_c1_up <- all_vis[all_vis$cluster == "c1",]
vis_c2_up <- all_vis[all_vis$cluster == "c2",]
vis_c3_up <- all_vis[all_vis$cluster == "c3",]
vis_c4_up <- all_vis[all_vis$cluster == "c4",]
vis_c5_up <- all_vis[all_vis$cluster == "c5",]


p1 <- plot_volcano(vis_c0_up,1,"Activated", c("ERAP2", "ARMC9", "ETV7", "HLA-K", "HDAC9", "TMEM204", "STAT1","IFNGR2","IRF1", "SOCS1", "SOCS3", "IFITM3"))
p2 <- plot_volcano(vis_c1_up,2, "Exhausted/Cytotoxic", c("IFITM3", "HDAC9", "ERAP2", "CPA5", "LMNA", "ITGB1", "FOXP1", "STAT1", "STAT1", "IFNGR2","IRF1", "SOCS1", "SOCS3", "IFITM3"))
p3 <- plot_volcano(vis_c2_up,3, "Naive", c("ERAP2", "TBC1D4", "DDIT4", "SOCS1", "IRF1", "STAT1", "STAT1", "IFNGR2","IRF1", "SOCS1", "SOCS3", "IFITM3"))
p4 <- plot_volcano(vis_c3_up,4, "MHC_Class_II",c("ERAP2", "HLA-K", "STAT1", "FOXP1", "TNFRSF4", "STAT1", "IFNGR2","IRF1", "SOCS1", "SOCS3", "IFITM3"))
p5 <- plot_volcano(vis_c4_up,5, "Effector", c("MIF", "TIMP1", "PPDPF", "IKZF3", "ETV7", "FOXP1", "STAT1", "STAT1", "IFNGR2","IRF1", "SOCS1", "SOCS3", "IFITM3"))
p6 <- plot_volcano(vis_c5_up,6, "Replicating", c("TNR", "UBE2C", "H3C2", "H1-5", "STAT1", "STAT1", "IFNGR2","IRF1", "SOCS1", "SOCS3", "IFITM3"))

p1

p2

p3

p4

p5

p6

4.11 Curating Gene Lists for Pathway Analysis

all_vis <- read.csv("/jsimonlab/users/bshim/Shuntaro_scRNA_TCR/analysis_052124/all_clusters_de.csv")

all_vis_split <- all_vis %>%
    group_by(cluster) %>%
    group_split()

all_vis_split_ranks <- lapply(all_vis_split, 
                                FUN = function(x) { x %>%
                                    dplyr::select(gene,logFC) %>%
                                    dplyr::arrange(logFC) %>%
                                    deframe()
                                    }
                        )
names(all_vis_split_ranks) <- paste0("Cluster", 
                                sapply(all_vis_split, 
                                FUN = function(x) { x %>% 
                                    pull(cluster) %>%
                                    unique()
                                    }
                                )
                            )

4.12 Buliding a Pathway Database for Pathway Analysis

c2 <- msigdbr::msigdbr(species="Homo sapiens",
        category = "C2")
Warning: The `category` argument of `msigdbr()` is deprecated as of msigdbr 10.0.0.
ℹ Please use the `collection` argument instead.
immunesig <- msigdbr::msigdbr(species="Homo sapiens",
        category = "C7", 
        subcategory = "IMMUNESIGDB")
Warning: The `subcategory` argument of `msigdbr()` is deprecated as of msigdbr 10.0.0.
ℹ Please use the `subcollection` argument instead.
go_pathway <- msigdbr::msigdbr(species="Homo sapiens",
        category = "C5")

reactome <- msigdbr::msigdbr(
  species = "Homo sapiens",
  category = "C2",
  subcategory = "CP:REACTOME"
)

hallmark <- msigdbr::msigdbr(species="Homo sapiens",
    category = "H")                         

# Get updated KEGG MEDICUS collection from GSEAtraining package 
km <- get_msigdb(version = "2024.1.Hs", 
    collection = "c2.cp.kegg_medicus",
    gene_id_type = "symbols")

# Combine into named list
# pathwaysToTest <- bind_rows(c2,immunesig,hallmark)
pathwaysToTest <- bind_rows(c2, immunesig, hallmark)

pathwaysToTest_split <- pathwaysToTest %>%
    dplyr::select(gs_name,gene_symbol) %>%
    group_by(gs_name) %>%
    group_split()

names(pathwaysToTest_split) <- sapply(pathwaysToTest_split, 
                                        FUN = function(x) { x %>% 
                                            pull(gs_name) %>%
                                            unique()
                                            }
                                        )


pathwaysToTest_split_list <- sapply(pathwaysToTest_split, 
                                    simplify = FALSE, 
                                    USE.NAMES = TRUE, 
                                    FUN = function(x) { x %>%
                                        pull(gene_symbol) %>%
                                        unique()
                                    }
                                )
# Add KEGG MEDICUS to the list
pathwaysToTest_split_list <- c(pathwaysToTest_split_list, km)

4.13 Screening All Genes to Detect Pathways That are Statistically Significant

set.seed(123)
fgseaRes <- sapply(all_vis_split_ranks, 
    simplify = FALSE, 
    USE.NAMES = TRUE, 
    FUN = function(x) {
        fgsea(pathways = pathwaysToTest_split_list, 
              stats = x,
              minSize = 5, # Note this is the intersection of genes in the ranked list and genes in the pathway
              maxSize = 1000,
              nproc = 1
              )
        }
    )
Warning in preparePathwaysAndStats(pathways, stats, minSize, maxSize, gseaParam, : There are ties in the preranked stats (0.03% of the list).
The order of those tied genes will be arbitrary, which may produce unexpected results.

  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |=                                                                     |   1%
  |                                                                            
  |=                                                                     |   2%
  |                                                                            
  |==                                                                    |   2%
  |                                                                            
  |==                                                                    |   3%
  |                                                                            
  |==                                                                    |   4%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |===                                                                   |   5%
  |                                                                            
  |====                                                                  |   5%
  |                                                                            
  |====                                                                  |   6%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |======                                                                |   9%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |=======                                                               |  11%
  |                                                                            
  |========                                                              |  11%
  |                                                                            
  |========                                                              |  12%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |=========                                                             |  13%
  |                                                                            
  |==========                                                            |  14%
  |                                                                            
  |==========                                                            |  15%
  |                                                                            
  |===========                                                           |  15%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |============                                                          |  18%
  |                                                                            
  |=============                                                         |  18%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |==============                                                        |  19%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |==============                                                        |  21%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |===============                                                       |  22%
  |                                                                            
  |================                                                      |  22%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |=================                                                     |  25%
  |                                                                            
  |==================                                                    |  25%
  |                                                                            
  |==================                                                    |  26%
  |                                                                            
  |===================                                                   |  26%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |===================                                                   |  28%
  |                                                                            
  |====================                                                  |  28%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |======================                                                |  32%
  |                                                                            
  |=======================                                               |  32%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |========================                                              |  35%
  |                                                                            
  |=========================                                             |  35%
  |                                                                            
  |=========================                                             |  36%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |===========================                                           |  38%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |============================                                          |  41%
  |                                                                            
  |=============================                                         |  41%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |==============================                                        |  42%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |===============================                                       |  45%
  |                                                                            
  |================================                                      |  45%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |=================================                                     |  47%
  |                                                                            
  |=================================                                     |  48%
  |                                                                            
  |==================================                                    |  48%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |===================================                                   |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |===================================                                   |  51%
  |                                                                            
  |====================================                                  |  51%
  |                                                                            
  |====================================                                  |  52%
  |                                                                            
  |=====================================                                 |  52%
  |                                                                            
  |=====================================                                 |  53%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |======================================                                |  55%
  |                                                                            
  |=======================================                               |  55%
  |                                                                            
  |=======================================                               |  56%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |========================================                              |  58%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |=========================================                             |  59%
  |                                                                            
  |==========================================                            |  59%
  |                                                                            
  |==========================================                            |  60%
  |                                                                            
  |===========================================                           |  61%
  |                                                                            
  |===========================================                           |  62%
  |                                                                            
  |============================================                          |  63%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |=============================================                         |  65%
  |                                                                            
  |==============================================                        |  65%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |===============================================                       |  68%
  |                                                                            
  |================================================                      |  68%
  |                                                                            
  |================================================                      |  69%
  |                                                                            
  |=================================================                     |  70%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |==================================================                    |  72%
  |                                                                            
  |===================================================                   |  72%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |===================================================                   |  74%
  |                                                                            
  |====================================================                  |  74%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |=====================================================                 |  75%
  |                                                                            
  |=====================================================                 |  76%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |======================================================                |  78%
  |                                                                            
  |=======================================================               |  78%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |========================================================              |  79%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |========================================================              |  81%
  |                                                                            
  |=========================================================             |  81%
  |                                                                            
  |=========================================================             |  82%
  |                                                                            
  |==========================================================            |  82%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |===========================================================           |  84%
  |                                                                            
  |===========================================================           |  85%
  |                                                                            
  |============================================================          |  85%
  |                                                                            
  |============================================================          |  86%
  |                                                                            
  |=============================================================         |  87%
  |                                                                            
  |=============================================================         |  88%
  |                                                                            
  |==============================================================        |  88%
  |                                                                            
  |==============================================================        |  89%
  |                                                                            
  |===============================================================       |  89%
  |                                                                            
  |===============================================================       |  90%
  |                                                                            
  |================================================================      |  91%
  |                                                                            
  |================================================================      |  92%
  |                                                                            
  |=================================================================     |  93%
  |                                                                            
  |==================================================================    |  94%
  |                                                                            
  |==================================================================    |  95%
  |                                                                            
  |===================================================================   |  95%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |====================================================================  |  96%
  |                                                                            
  |====================================================================  |  97%
  |                                                                            
  |====================================================================  |  98%
  |                                                                            
  |===================================================================== |  98%
  |                                                                            
  |===================================================================== |  99%
  |                                                                            
  |======================================================================| 100%


  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |=                                                                     |   1%
  |                                                                            
  |=                                                                     |   2%
  |                                                                            
  |==                                                                    |   2%
  |                                                                            
  |==                                                                    |   3%
  |                                                                            
  |==                                                                    |   4%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |===                                                                   |   5%
  |                                                                            
  |====                                                                  |   5%
  |                                                                            
  |====                                                                  |   6%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |=====                                                                 |   8%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |======                                                                |   9%
  |                                                                            
  |=======                                                               |   9%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |=======                                                               |  11%
  |                                                                            
  |========                                                              |  11%
  |                                                                            
  |========                                                              |  12%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |=========                                                             |  13%
  |                                                                            
  |==========                                                            |  14%
  |                                                                            
  |==========                                                            |  15%
  |                                                                            
  |===========                                                           |  15%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |============                                                          |  18%
  |                                                                            
  |=============                                                         |  18%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |==============                                                        |  19%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |==============                                                        |  21%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |===============                                                       |  22%
  |                                                                            
  |================                                                      |  22%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |=================                                                     |  25%
  |                                                                            
  |==================                                                    |  25%
  |                                                                            
  |==================                                                    |  26%
  |                                                                            
  |===================                                                   |  26%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |===================                                                   |  28%
  |                                                                            
  |====================                                                  |  28%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |======================                                                |  32%
  |                                                                            
  |=======================                                               |  32%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |========================                                              |  35%
  |                                                                            
  |=========================                                             |  35%
  |                                                                            
  |=========================                                             |  36%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |===========================                                           |  38%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |============================                                          |  39%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |=============================                                         |  41%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |==============================                                        |  42%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |===============================                                       |  45%
  |                                                                            
  |================================                                      |  45%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |=================================                                     |  47%
  |                                                                            
  |==================================                                    |  48%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |===================================                                   |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |===================================                                   |  51%
  |                                                                            
  |====================================                                  |  51%
  |                                                                            
  |====================================                                  |  52%
  |                                                                            
  |=====================================                                 |  53%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |======================================                                |  55%
  |                                                                            
  |=======================================                               |  55%
  |                                                                            
  |=======================================                               |  56%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |========================================                              |  58%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |=========================================                             |  59%
  |                                                                            
  |==========================================                            |  60%
  |                                                                            
  |==========================================                            |  61%
  |                                                                            
  |===========================================                           |  61%
  |                                                                            
  |===========================================                           |  62%
  |                                                                            
  |============================================                          |  62%
  |                                                                            
  |============================================                          |  63%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |=============================================                         |  65%
  |                                                                            
  |==============================================                        |  65%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |===============================================                       |  68%
  |                                                                            
  |================================================                      |  68%
  |                                                                            
  |================================================                      |  69%
  |                                                                            
  |=================================================                     |  70%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |==================================================                    |  72%
  |                                                                            
  |===================================================                   |  72%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |===================================================                   |  74%
  |                                                                            
  |====================================================                  |  74%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |=====================================================                 |  75%
  |                                                                            
  |=====================================================                 |  76%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |======================================================                |  78%
  |                                                                            
  |=======================================================               |  78%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |========================================================              |  79%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |========================================================              |  81%
  |                                                                            
  |=========================================================             |  81%
  |                                                                            
  |=========================================================             |  82%
  |                                                                            
  |==========================================================            |  82%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |===========================================================           |  84%
  |                                                                            
  |===========================================================           |  85%
  |                                                                            
  |============================================================          |  85%
  |                                                                            
  |============================================================          |  86%
  |                                                                            
  |=============================================================         |  87%
  |                                                                            
  |=============================================================         |  88%
  |                                                                            
  |==============================================================        |  88%
  |                                                                            
  |==============================================================        |  89%
  |                                                                            
  |===============================================================       |  89%
  |                                                                            
  |===============================================================       |  90%
  |                                                                            
  |===============================================================       |  91%
  |                                                                            
  |================================================================      |  91%
  |                                                                            
  |================================================================      |  92%
  |                                                                            
  |=================================================================     |  92%
  |                                                                            
  |=================================================================     |  93%
  |                                                                            
  |==================================================================    |  94%
  |                                                                            
  |==================================================================    |  95%
  |                                                                            
  |===================================================================   |  95%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |====================================================================  |  96%
  |                                                                            
  |====================================================================  |  97%
  |                                                                            
  |====================================================================  |  98%
  |                                                                            
  |===================================================================== |  98%
  |                                                                            
  |===================================================================== |  99%
  |                                                                            
  |======================================================================| 100%


  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |=                                                                     |   1%
  |                                                                            
  |=                                                                     |   2%
  |                                                                            
  |==                                                                    |   2%
  |                                                                            
  |==                                                                    |   3%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |===                                                                   |   5%
  |                                                                            
  |====                                                                  |   5%
  |                                                                            
  |====                                                                  |   6%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |=====                                                                 |   8%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |======                                                                |   9%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |========                                                              |  11%
  |                                                                            
  |========                                                              |  12%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |=========                                                             |  13%
  |                                                                            
  |==========                                                            |  14%
  |                                                                            
  |==========                                                            |  15%
  |                                                                            
  |===========                                                           |  15%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |============                                                          |  18%
  |                                                                            
  |=============                                                         |  18%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |===============                                                       |  22%
  |                                                                            
  |================                                                      |  22%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |=================                                                     |  25%
  |                                                                            
  |==================                                                    |  25%
  |                                                                            
  |==================                                                    |  26%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |===================                                                   |  28%
  |                                                                            
  |====================                                                  |  28%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |======================                                                |  32%
  |                                                                            
  |=======================                                               |  32%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |========================                                              |  35%
  |                                                                            
  |=========================                                             |  35%
  |                                                                            
  |=========================                                             |  36%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |===========================                                           |  38%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |=============================                                         |  41%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |==============================                                        |  42%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |===============================                                       |  45%
  |                                                                            
  |================================                                      |  45%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |=================================                                     |  47%
  |                                                                            
  |=================================                                     |  48%
  |                                                                            
  |==================================                                    |  48%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |====================================                                  |  51%
  |                                                                            
  |====================================                                  |  52%
  |                                                                            
  |=====================================                                 |  52%
  |                                                                            
  |=====================================                                 |  53%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |======================================                                |  55%
  |                                                                            
  |=======================================                               |  55%
  |                                                                            
  |=======================================                               |  56%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |========================================                              |  58%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |=========================================                             |  59%
  |                                                                            
  |==========================================                            |  60%
  |                                                                            
  |===========================================                           |  61%
  |                                                                            
  |===========================================                           |  62%
  |                                                                            
  |============================================                          |  62%
  |                                                                            
  |============================================                          |  63%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |=============================================                         |  65%
  |                                                                            
  |==============================================                        |  65%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |===============================================                       |  68%
  |                                                                            
  |================================================                      |  68%
  |                                                                            
  |================================================                      |  69%
  |                                                                            
  |=================================================                     |  70%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |==================================================                    |  72%
  |                                                                            
  |===================================================                   |  72%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |====================================================                  |  74%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |=====================================================                 |  75%
  |                                                                            
  |=====================================================                 |  76%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |======================================================                |  78%
  |                                                                            
  |=======================================================               |  78%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |=========================================================             |  81%
  |                                                                            
  |=========================================================             |  82%
  |                                                                            
  |==========================================================            |  82%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |===========================================================           |  84%
  |                                                                            
  |===========================================================           |  85%
  |                                                                            
  |============================================================          |  85%
  |                                                                            
  |============================================================          |  86%
  |                                                                            
  |=============================================================         |  87%
  |                                                                            
  |=============================================================         |  88%
  |                                                                            
  |==============================================================        |  88%
  |                                                                            
  |==============================================================        |  89%
  |                                                                            
  |===============================================================       |  90%
  |                                                                            
  |================================================================      |  91%
  |                                                                            
  |================================================================      |  92%
  |                                                                            
  |=================================================================     |  92%
  |                                                                            
  |=================================================================     |  93%
  |                                                                            
  |==================================================================    |  94%
  |                                                                            
  |==================================================================    |  95%
  |                                                                            
  |===================================================================   |  95%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |====================================================================  |  97%
  |                                                                            
  |====================================================================  |  98%
  |                                                                            
  |===================================================================== |  98%
  |                                                                            
  |===================================================================== |  99%
  |                                                                            
  |======================================================================| 100%
Warning in preparePathwaysAndStats(pathways, stats, minSize, maxSize, gseaParam, : There are ties in the preranked stats (0.02% of the list).
The order of those tied genes will be arbitrary, which may produce unexpected results.

  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |=                                                                     |   1%
  |                                                                            
  |=                                                                     |   2%
  |                                                                            
  |==                                                                    |   2%
  |                                                                            
  |==                                                                    |   3%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |===                                                                   |   5%
  |                                                                            
  |====                                                                  |   5%
  |                                                                            
  |====                                                                  |   6%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |=====                                                                 |   8%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |======                                                                |   9%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |========                                                              |  11%
  |                                                                            
  |========                                                              |  12%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |=========                                                             |  13%
  |                                                                            
  |==========                                                            |  14%
  |                                                                            
  |==========                                                            |  15%
  |                                                                            
  |===========                                                           |  15%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |============                                                          |  18%
  |                                                                            
  |=============                                                         |  18%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |===============                                                       |  22%
  |                                                                            
  |================                                                      |  22%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |=================                                                     |  25%
  |                                                                            
  |==================                                                    |  25%
  |                                                                            
  |==================                                                    |  26%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |===================                                                   |  28%
  |                                                                            
  |====================                                                  |  28%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |======================                                                |  32%
  |                                                                            
  |=======================                                               |  32%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |========================                                              |  35%
  |                                                                            
  |=========================                                             |  35%
  |                                                                            
  |=========================                                             |  36%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |===========================                                           |  38%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |=============================                                         |  41%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |==============================                                        |  42%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |===============================                                       |  45%
  |                                                                            
  |================================                                      |  45%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |=================================                                     |  47%
  |                                                                            
  |=================================                                     |  48%
  |                                                                            
  |==================================                                    |  48%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |====================================                                  |  51%
  |                                                                            
  |====================================                                  |  52%
  |                                                                            
  |=====================================                                 |  52%
  |                                                                            
  |=====================================                                 |  53%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |======================================                                |  55%
  |                                                                            
  |=======================================                               |  55%
  |                                                                            
  |=======================================                               |  56%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |========================================                              |  58%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |=========================================                             |  59%
  |                                                                            
  |==========================================                            |  60%
  |                                                                            
  |===========================================                           |  61%
  |                                                                            
  |===========================================                           |  62%
  |                                                                            
  |============================================                          |  62%
  |                                                                            
  |============================================                          |  63%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |=============================================                         |  65%
  |                                                                            
  |==============================================                        |  65%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |===============================================                       |  68%
  |                                                                            
  |================================================                      |  68%
  |                                                                            
  |================================================                      |  69%
  |                                                                            
  |=================================================                     |  70%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |==================================================                    |  72%
  |                                                                            
  |===================================================                   |  72%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |====================================================                  |  74%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |=====================================================                 |  75%
  |                                                                            
  |=====================================================                 |  76%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |======================================================                |  78%
  |                                                                            
  |=======================================================               |  78%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |=========================================================             |  81%
  |                                                                            
  |=========================================================             |  82%
  |                                                                            
  |==========================================================            |  82%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |===========================================================           |  84%
  |                                                                            
  |===========================================================           |  85%
  |                                                                            
  |============================================================          |  85%
  |                                                                            
  |============================================================          |  86%
  |                                                                            
  |=============================================================         |  87%
  |                                                                            
  |=============================================================         |  88%
  |                                                                            
  |==============================================================        |  88%
  |                                                                            
  |==============================================================        |  89%
  |                                                                            
  |===============================================================       |  90%
  |                                                                            
  |================================================================      |  91%
  |                                                                            
  |================================================================      |  92%
  |                                                                            
  |=================================================================     |  92%
  |                                                                            
  |=================================================================     |  93%
  |                                                                            
  |==================================================================    |  94%
  |                                                                            
  |==================================================================    |  95%
  |                                                                            
  |===================================================================   |  95%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |====================================================================  |  97%
  |                                                                            
  |====================================================================  |  98%
  |                                                                            
  |===================================================================== |  98%
  |                                                                            
  |===================================================================== |  99%
  |                                                                            
  |======================================================================| 100%
Warning in preparePathwaysAndStats(pathways, stats, minSize, maxSize, gseaParam, : There are ties in the preranked stats (0.02% of the list).
The order of those tied genes will be arbitrary, which may produce unexpected results.
Warning in fgseaMultilevel(pathways = pathways, stats = stats, minSize =
minSize, : There were 13 pathways for which P-values were not calculated
properly due to unbalanced (positive and negative) gene-level statistic values.
For such pathways pval, padj, NES, log2err are set to NA. You can try to
increase the value of the argument nPermSimple (for example set it nPermSimple
= 10000)

  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |=                                                                     |   1%
  |                                                                            
  |=                                                                     |   2%
  |                                                                            
  |==                                                                    |   2%
  |                                                                            
  |==                                                                    |   3%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |===                                                                   |   5%
  |                                                                            
  |====                                                                  |   5%
  |                                                                            
  |====                                                                  |   6%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |=====                                                                 |   8%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |======                                                                |   9%
  |                                                                            
  |=======                                                               |   9%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |=======                                                               |  11%
  |                                                                            
  |========                                                              |  11%
  |                                                                            
  |========                                                              |  12%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |=========                                                             |  13%
  |                                                                            
  |==========                                                            |  14%
  |                                                                            
  |==========                                                            |  15%
  |                                                                            
  |===========                                                           |  15%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |============                                                          |  18%
  |                                                                            
  |=============                                                         |  18%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |===============                                                       |  22%
  |                                                                            
  |================                                                      |  22%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |=================                                                     |  25%
  |                                                                            
  |==================                                                    |  25%
  |                                                                            
  |==================                                                    |  26%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |===================                                                   |  28%
  |                                                                            
  |====================                                                  |  28%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=====================                                                 |  29%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |=====================                                                 |  31%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |======================                                                |  32%
  |                                                                            
  |=======================                                               |  32%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |========================                                              |  35%
  |                                                                            
  |=========================                                             |  35%
  |                                                                            
  |=========================                                             |  36%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |===========================                                           |  38%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |=============================                                         |  41%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |==============================                                        |  42%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |===============================                                       |  45%
  |                                                                            
  |================================                                      |  45%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |=================================                                     |  47%
  |                                                                            
  |=================================                                     |  48%
  |                                                                            
  |==================================                                    |  48%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |===================================                                   |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |===================================                                   |  51%
  |                                                                            
  |====================================                                  |  51%
  |                                                                            
  |====================================                                  |  52%
  |                                                                            
  |=====================================                                 |  52%
  |                                                                            
  |=====================================                                 |  53%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |======================================                                |  55%
  |                                                                            
  |=======================================                               |  55%
  |                                                                            
  |=======================================                               |  56%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |========================================                              |  58%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |=========================================                             |  59%
  |                                                                            
  |==========================================                            |  60%
  |                                                                            
  |===========================================                           |  61%
  |                                                                            
  |===========================================                           |  62%
  |                                                                            
  |============================================                          |  62%
  |                                                                            
  |============================================                          |  63%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |=============================================                         |  65%
  |                                                                            
  |==============================================                        |  65%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |===============================================                       |  68%
  |                                                                            
  |================================================                      |  68%
  |                                                                            
  |================================================                      |  69%
  |                                                                            
  |=================================================                     |  69%
  |                                                                            
  |=================================================                     |  70%
  |                                                                            
  |=================================================                     |  71%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |==================================================                    |  72%
  |                                                                            
  |===================================================                   |  72%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |====================================================                  |  74%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |=====================================================                 |  75%
  |                                                                            
  |=====================================================                 |  76%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |======================================================                |  78%
  |                                                                            
  |=======================================================               |  78%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |=========================================================             |  81%
  |                                                                            
  |=========================================================             |  82%
  |                                                                            
  |==========================================================            |  82%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |===========================================================           |  84%
  |                                                                            
  |===========================================================           |  85%
  |                                                                            
  |============================================================          |  85%
  |                                                                            
  |============================================================          |  86%
  |                                                                            
  |=============================================================         |  87%
  |                                                                            
  |=============================================================         |  88%
  |                                                                            
  |==============================================================        |  88%
  |                                                                            
  |==============================================================        |  89%
  |                                                                            
  |===============================================================       |  89%
  |                                                                            
  |===============================================================       |  90%
  |                                                                            
  |===============================================================       |  91%
  |                                                                            
  |================================================================      |  91%
  |                                                                            
  |================================================================      |  92%
  |                                                                            
  |=================================================================     |  92%
  |                                                                            
  |=================================================================     |  93%
  |                                                                            
  |==================================================================    |  94%
  |                                                                            
  |==================================================================    |  95%
  |                                                                            
  |===================================================================   |  95%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |====================================================================  |  97%
  |                                                                            
  |====================================================================  |  98%
  |                                                                            
  |===================================================================== |  98%
  |                                                                            
  |===================================================================== |  99%
  |                                                                            
  |======================================================================| 100%
Warning in fgseaMultilevel(pathways = pathways, stats = stats, minSize =
minSize, : For some of the pathways the P-values were likely overestimated. For
such pathways log2err is set to NA.
Warning in fgseaMultilevel(pathways = pathways, stats = stats, minSize =
minSize, : There were 4 pathways for which P-values were not calculated
properly due to unbalanced (positive and negative) gene-level statistic values.
For such pathways pval, padj, NES, log2err are set to NA. You can try to
increase the value of the argument nPermSimple (for example set it nPermSimple
= 10000)

  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |=                                                                     |   1%
  |                                                                            
  |=                                                                     |   2%
  |                                                                            
  |==                                                                    |   2%
  |                                                                            
  |==                                                                    |   3%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |===                                                                   |   5%
  |                                                                            
  |====                                                                  |   5%
  |                                                                            
  |====                                                                  |   6%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |=====                                                                 |   8%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |======                                                                |   9%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |========                                                              |  11%
  |                                                                            
  |========                                                              |  12%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |=========                                                             |  13%
  |                                                                            
  |==========                                                            |  14%
  |                                                                            
  |==========                                                            |  15%
  |                                                                            
  |===========                                                           |  15%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |============                                                          |  18%
  |                                                                            
  |=============                                                         |  18%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |===============                                                       |  22%
  |                                                                            
  |================                                                      |  22%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |=================                                                     |  25%
  |                                                                            
  |==================                                                    |  25%
  |                                                                            
  |==================                                                    |  26%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |===================                                                   |  28%
  |                                                                            
  |====================                                                  |  28%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |======================                                                |  32%
  |                                                                            
  |=======================                                               |  32%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |========================                                              |  35%
  |                                                                            
  |=========================                                             |  35%
  |                                                                            
  |=========================                                             |  36%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |===========================                                           |  38%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |=============================                                         |  41%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |==============================                                        |  42%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |===============================                                       |  45%
  |                                                                            
  |================================                                      |  45%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |=================================                                     |  47%
  |                                                                            
  |=================================                                     |  48%
  |                                                                            
  |==================================                                    |  48%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |====================================                                  |  51%
  |                                                                            
  |====================================                                  |  52%
  |                                                                            
  |=====================================                                 |  52%
  |                                                                            
  |=====================================                                 |  53%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |======================================                                |  55%
  |                                                                            
  |=======================================                               |  55%
  |                                                                            
  |=======================================                               |  56%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |========================================                              |  58%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |=========================================                             |  59%
  |                                                                            
  |==========================================                            |  60%
  |                                                                            
  |===========================================                           |  61%
  |                                                                            
  |===========================================                           |  62%
  |                                                                            
  |============================================                          |  62%
  |                                                                            
  |============================================                          |  63%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |=============================================                         |  65%
  |                                                                            
  |==============================================                        |  65%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |===============================================                       |  68%
  |                                                                            
  |================================================                      |  68%
  |                                                                            
  |================================================                      |  69%
  |                                                                            
  |=================================================                     |  70%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |==================================================                    |  72%
  |                                                                            
  |===================================================                   |  72%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |====================================================                  |  74%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |=====================================================                 |  75%
  |                                                                            
  |=====================================================                 |  76%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |======================================================                |  78%
  |                                                                            
  |=======================================================               |  78%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |=========================================================             |  81%
  |                                                                            
  |=========================================================             |  82%
  |                                                                            
  |==========================================================            |  82%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |===========================================================           |  84%
  |                                                                            
  |===========================================================           |  85%
  |                                                                            
  |============================================================          |  85%
  |                                                                            
  |============================================================          |  86%
  |                                                                            
  |=============================================================         |  87%
  |                                                                            
  |=============================================================         |  88%
  |                                                                            
  |==============================================================        |  88%
  |                                                                            
  |==============================================================        |  89%
  |                                                                            
  |===============================================================       |  90%
  |                                                                            
  |================================================================      |  91%
  |                                                                            
  |================================================================      |  92%
  |                                                                            
  |=================================================================     |  92%
  |                                                                            
  |=================================================================     |  93%
  |                                                                            
  |==================================================================    |  94%
  |                                                                            
  |==================================================================    |  95%
  |                                                                            
  |===================================================================   |  95%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |====================================================================  |  97%
  |                                                                            
  |====================================================================  |  98%
  |                                                                            
  |===================================================================== |  98%
  |                                                                            
  |===================================================================== |  99%
  |                                                                            
  |======================================================================| 100%
Warning in fgseaMultilevel(pathways = pathways, stats = stats, minSize =
minSize, : For some of the pathways the P-values were likely overestimated. For
such pathways log2err is set to NA.
Warning in fgseaMultilevel(pathways = pathways, stats = stats, minSize =
minSize, : For some pathways, in reality P-values are less than 1e-50. You can
set the `eps` argument to zero for better estimation.

4.14 Screening pathways that are phenotype specific

fgsea_df <- bind_rows(fgseaRes, .id = "sub.cluster") %>%
  as_tibble() %>%
  mutate(leadingEdgeGenes = map_chr(leadingEdge, toString)) %>%
  dplyr::select(-leadingEdge) %>%
  dplyr::arrange(sub.cluster, padj,NES)

# pathways with specific NES signs.
get_top_sig <- function(df, cluster, nes_sign) {
  df %>%
    filter(sign(NES) == nes_sign,sub.cluster == cluster) %>%
    arrange(padj) 
}

Il12_TH1_Paths <- read.csv("/jsimonlab/users/bshim/Shuntaro_scRNA_TCR/publication_figure/gsea_filtered_IL12_TH1_IFNG.csv")
topSigPathways_c1_IL12 <- get_top_sig(Il12_TH1_Paths, "Clusterc1", -1)
topSigPathways_c4_IL12 <- get_top_sig(Il12_TH1_Paths, "Clusterc4",  1)

4.15 Plotting top 10 pathways from each cluster

##NES negatives are upregulated in NR 
##NES positives are upregulated in R
top_n <- 10 # change as needed

neg_pathways <- fgsea_df %>%
  filter(NES < 0, padj < 0.05) %>%
  group_by(pathway) %>%
  filter(n_distinct(sub.cluster) > 0) %>%
  ungroup() %>%
  group_by(sub.cluster) %>%
  arrange(padj) %>%
  slice_head(n=top_n) %>%
  ungroup()

pos_pathways <- fgsea_df %>%
  filter(NES > 0, padj < 0.05) %>%
  group_by(pathway) %>%
  filter(n_distinct(sub.cluster) > 0) %>%
  ungroup() %>%
  group_by(sub.cluster) %>%
  arrange(padj) %>%
  slice_head(n=top_n) %>%
  ungroup()

pathways_c1 <- neg_pathways$pathway %>% unique()
pathways_c4 <- pos_pathways$pathway %>% unique()

p_c2 <- fgsea_df %>%
    as_tibble() %>%
    mutate(
      cluster = as.integer(gsub("^Clusterc", "", sub.cluster)),
      cluster_label = paste0("Cluster", cluster + 1)
    ) %>%
      mutate(logP = ifelse(padj < 0.05, -log10(padj), 0)) %>%
      dplyr::filter(pathway %in% pathways_c1) %>%
    ggplot(aes(x = cluster_label, y = pathway)) +
    geom_point(aes(color = NES, size = logP, alpha = I(ifelse(logP < -log10(0.1), 0, 1)))) +
    scale_size_continuous("-log10 adj p", range = c(3, 15), breaks = c(1.3, 5, 10, 20, 30)) +
    scale_color_gradient2(low = "blue", mid = "white", high = "red", limits=c(-3,3), midpoint = 0, oob = scales::squish) +
    theme_bw()  +
    scale_y_discrete(position = "right") +
    ylab("") +
    xlab("") +
    theme(
      axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
      strip.text.y.left = element_text(angle = 0),
      axis.title = element_text(size = 40),
      axis.text = element_text(size = 40),
      plot.title = element_text(size = 40, face = "bold", hjust = 0.5),
      legend.title = element_text(size = 40, face = "bold"),
      legend.text = element_text(size = 40)
    ) +
guides(
color = guide_colorbar(
  title = "NES\n(Responder ↑ | ↓ Non-responder)",
  title.position = "top",   
  barwidth = 5,
  barheight = 35,           
  title.theme = element_text(
    size = 40, face = "bold",
    margin = margin(b = 20)
  ),
  label.theme = element_text(
    size = 40,
    margin = margin(t = 25),
    lineheight = 15
  )
)
)

p_c5 <- fgsea_df %>%
    as_tibble() %>%
    mutate(
      cluster = as.integer(gsub("^Clusterc", "", sub.cluster)),
      cluster_label = paste0("Cluster", cluster + 1)
    ) %>%
      mutate(logP = ifelse(padj < 0.05, -log10(padj), 0)) %>%
      dplyr::filter(pathway %in% pathways_c4) %>%
    ggplot(aes(x = cluster_label, y = pathway)) +
    geom_point(aes(color = NES, size = logP, alpha = I(ifelse(logP < -log10(0.1), 0, 1)))) +
    scale_size_continuous("-log10 adj p", range = c(3, 15), breaks = c(1.3, 5, 10, 20, 30)) +
    scale_color_gradient2(low = "blue", mid = "white", high = "red", limits=c(-3,3), midpoint = 0, oob = scales::squish) +
    theme_bw()  +
    scale_y_discrete(position = "right") +
    ylab("") +
    xlab("") +
    theme(
      axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
      strip.text.y.left = element_text(angle = 0),
      axis.title = element_text(size = 35),
      axis.text = element_text(size = 35),
      plot.title = element_text(size = 40, face = "bold", hjust = 0.5),
      legend.title = element_text(size = 40, face = "bold"),
      legend.text = element_text(size = 40)
    ) +
guides(
color = guide_colorbar(
  title = "NES\n(Responder ↑ | ↓ Non-responder)",
  title.position = "top",   
  barwidth = 5,
  barheight = 35,           
  title.theme = element_text(
    size = 40, face = "bold",
    margin = margin(b = 20)
  ),
  label.theme = element_text(
    size = 40,
    margin = margin(t = 25),
    lineheight = 15
  )
)
)

p_c2
Warning: Removed 2 rows containing missing values or values outside the scale range
(`geom_point()`).

p_c5

4.16 Building IL12/TH1 Specific Pathway Lists

IL12 <- Il12_TH1_Paths %>%
  as_tibble() %>%
  mutate(
    cluster = as.integer(gsub("^Clusterc", "", sub.cluster)),
    cluster_label = paste0("Cluster", cluster + 1),
    logP = ifelse(padj < 0.1, -log10(padj), 0)
  ) %>%
  filter(pathway %in% topSigPathways_c1_IL12$pathway) %>%
  {
    # Grab example pathway name (to use for dummy rows) -> this is to fill in clusters with no significant IL12 / TH1 Pathways
    ex_pathway <- .$pathway[1]

    # Define all desired clusters
    all_clusters <- paste0("Clusterc", 0:5)
    # Find which clusters are missing
    # Detect missing ones
    missing_clusters <- setdiff(all_clusters, unique(.$sub.cluster))

    # Build dummy rows for missing clusters
    dummy_rows <- tibble(
      sub.cluster = missing_clusters,
      pathway = ex_pathway,
      padj = 1,
      NES = 0,
      cluster = as.integer(gsub("^Clusterc", "", missing_clusters)),
      cluster_label = paste0("Cluster", as.integer(gsub("^Clusterc", "", missing_clusters)) + 1),
      logP = 0
    )

    # Combine original + dummy
    bind_rows(., dummy_rows)
  }

4.17 Plotting IL12 / TH1 specific pathways

p <- IL12 %>%
    ggplot(aes(x = cluster_label, y = pathway)) +
    geom_point(aes(color = NES, size = logP, alpha = I(ifelse(logP < -log10(0.1), 0, 1)))) +
    scale_size_continuous("-log10 adj p", range = c(3, 15), breaks = c(1.3, 5, 10, 20, 30)) +
    scale_color_gradient2(low = "blue", mid = "white", high = "red", limits=c(-3,3), midpoint = 0, oob = scales::squish) +
    theme_bw()  +
    scale_y_discrete(position = "right") +
    ylab("") +
    xlab("") +
    theme(
      axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
      strip.text.y.left = element_text(angle = 0),
      axis.title = element_text(size = 55),
      axis.text = element_text(size = 55),
      plot.title = element_text(size = 55, face = "bold", hjust = 0.5),
      legend.title = element_text(size = 60, face = "bold"),
      legend.text = element_text(size = 60)
    ) +
guides(
color = guide_colorbar(
  title = "NES\n(Responder ↑ | ↓ Non-responder)",
  title.position = "top",   
  barwidth = 5,
  barheight = 35,           
  title.theme = element_text(
    size = 50, face = "bold",
    margin = margin(b = 20) 
  ),
  label.theme = element_text(
    size = 60,
    margin = margin(t = 25), 
    lineheight = 15
  )
)
)

p

sessionInfo()
R version 4.3.2 (2023-10-31)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Rocky Linux 8.10 (Green Obsidian)

Matrix products: default
BLAS/LAPACK: /usr/lib64/libopenblasp-r0.3.15.so;  LAPACK version 3.9.0

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       

time zone: America/New_York
tzcode source: system (glibc)

attached base packages:
[1] stats4    stats     graphics  grDevices utils     datasets  methods  
[8] base     

other attached packages:
 [1] EnhancedVolcano_1.13.2      ggrepel_0.9.6              
 [3] GSEAtraining_3.20.0         fgsea_1.28.0               
 [5] msigdbr_10.0.2              princurve_2.1.6            
 [7] muscat_1.18.0               lubridate_1.9.4            
 [9] forcats_1.0.0               stringr_1.5.1              
[11] dplyr_1.1.4                 purrr_1.0.2                
[13] readr_2.1.5                 tidyr_1.3.1                
[15] tibble_3.2.1                ggplot2_3.5.1              
[17] tidyverse_2.0.0             limma_3.58.1               
[19] scuttle_1.12.0              SingleCellExperiment_1.24.0
[21] SummarizedExperiment_1.32.0 Biobase_2.62.0             
[23] GenomicRanges_1.54.1        GenomeInfoDb_1.38.8        
[25] IRanges_2.36.0              S4Vectors_0.40.2           
[27] BiocGenerics_0.48.1         MatrixGenerics_1.14.0      
[29] matrixStats_1.5.0           Seurat_5.1.0               
[31] SeuratObject_5.0.2          sp_2.2-0                   

loaded via a namespace (and not attached):
  [1] R.methodsS3_1.8.2         dichromat_2.0-0.1        
  [3] progress_1.2.3            goftest_1.2-3            
  [5] DT_0.33                   Biostrings_2.72.1        
  [7] TH.data_1.1-3             vctrs_0.6.5              
  [9] spatstat.random_3.3-2     digest_0.6.37            
 [11] png_0.1-8                 corpcor_1.6.10           
 [13] shape_1.4.6.1             deldir_2.0-4             
 [15] parallelly_1.43.0         MASS_7.3-60.0.1          
 [17] reshape2_1.4.4            httpuv_1.6.15            
 [19] foreach_1.5.2             withr_3.0.2              
 [21] xfun_0.52                 survival_3.8-3           
 [23] memoise_2.0.1             ggbeeswarm_0.7.2         
 [25] emmeans_1.10.4            zoo_1.8-13               
 [27] GlobalOptions_0.1.2       gtools_3.9.5             
 [29] pbapply_1.7-2             R.oo_1.27.0              
 [31] prettyunits_1.2.0         KEGGREST_1.44.1          
 [33] promises_1.3.0            httr_1.4.7               
 [35] globals_0.16.3            fitdistrplus_1.2-2       
 [37] rstudioapi_0.17.1         miniUI_0.1.1.1           
 [39] generics_0.1.3            babelgene_22.9           
 [41] zlibbioc_1.48.2           ScaledMatrix_1.10.0      
 [43] polyclip_1.10-7           GenomeInfoDbData_1.2.11  
 [45] SparseArray_1.4.8         xtable_1.8-4             
 [47] doParallel_1.0.17         evaluate_1.0.3           
 [49] S4Arrays_1.4.1            hms_1.1.3                
 [51] irlba_2.3.5.1             colorspace_2.1-1         
 [53] ROCR_1.0-11               reticulate_1.31          
 [55] spatstat.data_3.1-2       magrittr_2.0.3           
 [57] lmtest_0.9-40             later_1.4.1              
 [59] viridis_0.6.5             lattice_0.22-7           
 [61] spatstat.geom_3.3-2       future.apply_1.11.3      
 [63] scattermore_1.2           cowplot_1.1.3.9000       
 [65] RcppAnnoy_0.0.22          pillar_1.10.1            
 [67] nlme_3.1-168              iterators_1.0.14         
 [69] SeuratWrappers_0.3.19     caTools_1.18.3           
 [71] compiler_4.3.2            beachmat_2.18.1          
 [73] RSpectra_0.16-2           stringi_1.8.7            
 [75] tensor_1.5                minqa_1.2.8              
 [77] plyr_1.8.9                crayon_1.5.3             
 [79] abind_1.4-8               scater_1.30.1            
 [81] blme_1.0-6                locfit_1.5-9.10          
 [83] bit_4.0.5                 sandwich_3.1-1           
 [85] fastmatch_1.1-6           codetools_0.2-20         
 [87] multcomp_1.4-28           BiocSingular_1.18.0      
 [89] GetoptLong_1.0.5          plotly_4.10.4            
 [91] remaCor_0.0.18            mime_0.13                
 [93] splines_4.3.2             circlize_0.4.16          
 [95] Rcpp_1.1.0                fastDummies_1.7.4        
 [97] sparseMatrixStats_1.14.0  knitr_1.50               
 [99] blob_1.2.4                clue_0.3-66              
[101] lme4_1.1-37               listenv_0.9.1            
[103] DelayedMatrixStats_1.24.0 Rdpack_2.6.3             
[105] estimability_1.5.1        Matrix_1.6-5             
[107] statmod_1.5.0             tzdb_0.5.0               
[109] fANCOVA_0.6-1             pkgconfig_2.0.3          
[111] tools_4.3.2               cachem_1.0.8             
[113] RhpcBLASctl_0.23-42       rbibutils_2.3            
[115] RSQLite_2.3.7             viridisLite_0.4.2        
[117] DBI_1.2.3                 numDeriv_2016.8-1.1      
[119] fastmap_1.2.0             rmarkdown_2.29           
[121] scales_1.4.0              grid_4.3.2               
[123] ica_1.0-3                 broom_1.0.8              
[125] patchwork_1.2.0           coda_0.19-4.1            
[127] BiocManager_1.30.25       dotCall64_1.2            
[129] RANN_2.6.2                farver_2.1.2             
[131] reformulas_0.4.0          aod_1.3.3                
[133] mgcv_1.9-3                msigdbdf_24.1.1          
[135] cli_3.6.4                 leiden_0.4.3.1           
[137] lifecycle_1.0.4           uwot_0.2.3               
[139] glmmTMB_1.1.9             mvtnorm_1.3-3            
[141] backports_1.5.0           BiocParallel_1.36.0      
[143] timechange_0.3.0          gtable_0.3.5             
[145] rjson_0.2.23              ggridges_0.5.6           
[147] progressr_0.14.0          parallel_4.3.2           
[149] jsonlite_2.0.0            edgeR_4.0.16             
[151] RcppHNSW_0.6.0            bitops_1.0-9             
[153] bit64_4.0.5               assertthat_0.2.1         
[155] Rtsne_0.17                spatstat.utils_3.1-1     
[157] BiocNeighbors_1.20.2      spatstat.univar_3.0-1    
[159] R.utils_2.13.0            pbkrtest_0.5.3           
[161] lazyeval_0.2.2            shiny_1.9.1              
[163] htmltools_0.5.8.1         sctransform_0.4.1        
[165] glue_1.8.0                spam_2.11-1              
[167] XVector_0.42.0            RCurl_1.98-1.17          
[169] gridExtra_2.3             EnvStats_3.0.0           
[171] boot_1.3-31               igraph_1.5.1             
[173] variancePartition_1.34.0  TMB_1.9.17               
[175] R6_2.6.1                  DESeq2_1.42.1            
[177] gplots_3.2.0              labeling_0.4.3           
[179] cluster_2.1.8.1           nloptr_2.0.3             
[181] DelayedArray_0.28.0       tidyselect_1.2.1         
[183] vipor_0.4.7               AnnotationDbi_1.66.0     
[185] future_1.34.0             rsvd_1.0.5               
[187] KernSmooth_2.23-26        data.table_1.17.0        
[189] htmlwidgets_1.6.4         ComplexHeatmap_2.18.0    
[191] RColorBrewer_1.1-3        rlang_1.1.5              
[193] spatstat.sparse_3.1-0     spatstat.explore_3.3-3   
[195] lmerTest_3.1-3            remotes_2.5.0            
[197] beeswarm_0.4.0