Last updated: 2025-02-24

Checks: 6 1

Knit directory: CX5461_Project/

This reproducible R Markdown analysis was created with workflowr (version 1.7.1). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


The R Markdown file has unstaged changes. To know which version of the R Markdown file created these results, you’ll want to first commit it to the Git repo. If you’re still working on the analysis, you can ignore this warning. When you’re finished, you can run wflow_publish to commit the R Markdown file and build the HTML.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20250129) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version c98542a. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .RData
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/

Unstaged changes:
    Modified:   analysis/Corrmotif_all_GO.Rmd

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/Corrmotif_all_GO.Rmd) and HTML (docs/Corrmotif_all_GO.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
Rmd fc2db42 sayanpaul01 2025-02-24 Commit
html fc2db42 sayanpaul01 2025-02-24 Commit
Rmd 2b163ba sayanpaul01 2025-02-24 Commit

📌 Load Required Libraries

library(tidyverse) 
library(ggfortify)
library(ggplot2)
library(cluster)
library(edgeR)
library(limma)
library(Homo.sapiens)
library(BiocParallel)
library(qvalue)
library(pheatmap)
library(clusterProfiler)
library(AnnotationDbi)
library(org.Hs.eg.db)
library(RColorBrewer)
library(readr)
library(TxDb.Hsapiens.UCSC.hg38.knownGene)
library(DOSE)

# Load UCSC transcript database
txdb <- TxDb.Hsapiens.UCSC.hg38.knownGene

📌 Read and Process Data

# Load the saved datasets
prob_all_1 <- read.csv("data/prob_all_1.csv")$Entrez_ID
prob_all_2 <- read.csv("data/prob_all_2.csv")$Entrez_ID
prob_all_3 <- read.csv("data/prob_all_3.csv")$Entrez_ID
prob_all_4 <- read.csv("data/prob_all_4.csv")$Entrez_ID

CX_0.1_3 <- read.csv("data/DEGs/Toptable_CX_0.1_3.csv")
background<-as.character(CX_0.1_3$Entrez_ID)

📌 Non response

📌 Non response GO Enrichment Clusterprofiler

# Perform GO enrichment analysis for BP, MF, and CC
go_enrichment_BP <- enrichGO(gene = prob_all_1,
                             OrgDb = org.Hs.eg.db,
                             keyType = "ENTREZID",
                             universe = background,
                             ont = "BP",
                             pvalueCutoff = 0.05)

go_enrichment_MF <- enrichGO(gene = prob_all_1,
                             OrgDb = org.Hs.eg.db,
                             keyType = "ENTREZID",
                             universe = background,
                             ont = "MF",
                             pvalueCutoff = 0.05)

go_enrichment_CC <- enrichGO(gene = prob_all_1,
                             OrgDb = org.Hs.eg.db,
                             keyType = "ENTREZID",
                             universe = background,
                             ont = "CC",
                             pvalueCutoff = 0.05)

# Convert each enrichment result to a tibble, add a category column, and select top 20 terms
process_enrichment_tibble <- function(enrichment, category) {
  if (is.null(enrichment) || nrow(as.data.frame(enrichment)) == 0) {
    return(tibble(Description = "No enriched terms", neglog = 0, Category = category))
  } else {
    enrichment %>%
      as_tibble() %>%
      mutate(Category = category,
             neglog = -log(p.adjust)) %>% # Add -log(p.adjust) column
      arrange(desc(neglog)) %>%          # Sort by -log(p.adjust)
      slice(1:20)                        # Select top 20 terms
  }
}

BP_Tibble <- process_enrichment_tibble(go_enrichment_BP, "Biological Process")
MF_Tibble <- process_enrichment_tibble(go_enrichment_MF, "Molecular Function")
CC_Tibble <- process_enrichment_tibble(go_enrichment_CC, "Cellular Component")

# Combine all tibbles
combined_GO_Tibble <- bind_rows(BP_Tibble, MF_Tibble, CC_Tibble)
# Function to generate enrichment plots
process_enrichment_plot <- function(tibble, title, color) {
  ggplot(data = tibble, aes(x = neglog, y = reorder(Description, neglog))) +
    geom_bar(stat = "identity", fill = color) +
    labs(x = "-log(p-adjust)",
         y = title,
         title = paste("Top 20", title, "GO Terms")) +
    theme_minimal() +
    theme(
      axis.text.x = element_text(size = 12, face = "bold", colour = "black", angle = 45, hjust = 1),
      axis.text.y = element_text(size = 12, face = "bold", colour = "black"),
      axis.title.x = element_text(size = 14, face = "bold", colour = "black"),
      axis.title.y = element_text(size = 14, face = "bold", colour = "black"),
      plot.title = element_text(size = 14, face = "bold", colour = "black"),
      panel.border = element_rect(colour = "black", fill = NA, size = 0.3)
    ) +
    xlim(c(0, max(tibble$neglog) + 1))
}

# Generate separate plots
plot_BP <- process_enrichment_plot(BP_Tibble, "Biological Process", "#2E86C1")
Warning: The `size` argument of `element_rect()` is deprecated as of ggplot2 3.4.0.
ℹ Please use the `linewidth` argument instead.
This warning is displayed once every 8 hours.
Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
generated.
plot_MF <- process_enrichment_plot(MF_Tibble, "Molecular Function", "#28B463")
plot_CC <- process_enrichment_plot(CC_Tibble, "Cellular Component", "#D35400")

# Combine the plots using patchwork
combined_plot <- plot_BP / plot_MF / plot_CC

# Display the combined plot
combined_plot

Version Author Date
fc2db42 sayanpaul01 2025-02-24

📌 Non response GO Enrichment g:Profiler

# Load the gprofiler2 package
library(gprofiler2)
Warning: package 'gprofiler2' was built under R version 4.3.3
library(ggplot2)
library(dplyr)
library(patchwork)
Warning: package 'patchwork' was built under R version 4.3.3
# Perform GO enrichment analysis with gprofiler2
gost_results <- gost(
  query = prob_all_1,           # List of input genes (prob_all_1)
  organism = "hsapiens",   # Human organism
  user_threshold = 0.05,   # Adjusted p-value cutoff
  correction_method = "fdr", # Multiple testing correction
  domain_scope = "custom", # Use custom background
  custom_bg = background,    # Background set of genes
  sources = c("GO:BP", "GO:MF", "GO:CC") # Analyze GO categories
)

# Check if enrichment results exist
if (is.null(gost_results$result) || nrow(gost_results$result) == 0) {
  # If no enriched terms, create a placeholder dataframe
  combined_results <- tibble(
    term_name = "No enriched terms",
    p.adjust = NA,
    source = "N/A",
    Category = "N/A"
  )
} else {
  # Convert results to a data frame
  gost_results_df <- gost_results$result

  # Add a column for adjusted p-value
  gost_results_df <- gost_results_df %>%
    rename(p.adjust = p_value)

  # Separate results for BP, MF, and CC
  BP_results <- gost_results_df %>%
    filter(source == "GO:BP") %>%
    mutate(Category = "Biological Process")

  MF_results <- gost_results_df %>%
    filter(source == "GO:MF") %>%
    mutate(Category = "Molecular Function")

  CC_results <- gost_results_df %>%
    filter(source == "GO:CC") %>%
    mutate(Category = "Cellular Component")

  # Select the top 20 terms by adjusted p-value for each category
  top_BP <- BP_results %>%
    arrange(p.adjust) %>%
    slice_head(n = 20)

  top_MF <- MF_results %>%
    arrange(p.adjust) %>%
    slice_head(n = 20)

  top_CC <- CC_results %>%
    arrange(p.adjust) %>%
    slice_head(n = 20)

  # Combine all categories
  combined_results <- bind_rows(top_BP, top_MF, top_CC)
}

# Ensure all columns are atomic types for CSV export
combined_results_clean <- combined_results %>%
  mutate(across(everything(), ~ if (is.list(.)) sapply(., toString) else .))

# Function for plotting top terms
plot_gprofiler_results <- function(data, title, color) {
  ggplot(data, aes(x = -log10(p.adjust), y = reorder(term_name, -log10(p.adjust)))) +
    geom_bar(stat = "identity", fill = color) +
    labs(
      x = "-log10(Adjusted p-value)",
      y = title,
      title = paste("Top 20", title, "GO Terms")
    ) +
    theme_minimal() +
    theme(
      axis.text.x = element_text(size = 12, face = "bold", colour = "black", angle = 45, hjust = 1),
      axis.text.y = element_text(size = 12, face = "bold", colour = "black"),
      axis.title.x = element_text(size = 14, face = "bold", colour = "black"),
      axis.title.y = element_text(size = 14, face = "bold", colour = "black"),
      plot.title = element_text(size = 14, face = "bold", colour = "black"),
      panel.border = element_rect(colour = "black", fill = NA, size = 0.3)
    )
}

# Check if there are enrichment terms to plot
if (nrow(combined_results) == 1 && combined_results$term_name == "No enriched terms") {
  message("No enriched GO terms found for the input gene set.")
} else {
  # Plot the top 20 terms for each category
  plot_BP <- plot_gprofiler_results(top_BP, "Biological Process", "#2E86C1")
  plot_MF <- plot_gprofiler_results(top_MF, "Molecular Function", "#28B463")
  plot_CC <- plot_gprofiler_results(top_CC, "Cellular Component", "#D35400")

  # Combine the plots using patchwork
  combined_plot <- plot_BP / plot_MF / plot_CC

  # Display the combined plot
  combined_plot
}

Version Author Date
fc2db42 sayanpaul01 2025-02-24

📌 Non response Pathway Enrichment

# Load required libraries
library(clusterProfiler)
library(org.Hs.eg.db) # Required for enrichPathway
library(gprofiler2)
library(ggplot2)
library(dplyr)
library(patchwork)
library(ReactomePA)
Warning: package 'ReactomePA' was built under R version 4.3.1
# Function for ClusterProfiler Reactome & KEGG Analysis
process_clusterProfiler <- function(gene_set, background, category, color, y_title) {
  # Perform enrichment based on the selected category
  if (category == "Reactome") {
    enrichment <- enrichPathway(
      gene = gene_set,
      organism = "human",
      pvalueCutoff = 0.05,
      pAdjustMethod = "BH",
      universe = background
    )
  } else if (category == "KEGG") {
    enrichment <- enrichKEGG(
      gene = gene_set,
      organism = "hsa",
      pvalueCutoff = 0.05,
      pAdjustMethod = "BH",
      universe = background
    )
  }
  
  # Check if enrichment results exist
  if (is.null(enrichment) || nrow(as.data.frame(enrichment)) == 0) {
    message(paste("No significant enrichment found for", category, "in ClusterProfiler"))
    return(NULL)
  }
  
  # Convert results to tibble and process top 20 terms
  enrichment_tibble <- as_tibble(as.data.frame(enrichment)) %>%
    mutate(Category = category,
           neglog = -log10(p.adjust)) %>%  # Compute -log10(p.adjust)
    arrange(desc(neglog)) %>%
    slice_head(n = min(20, nrow(.)))  # Ensure safe slicing
  
  # Generate plot
  plot <- ggplot(enrichment_tibble, aes(x = neglog, y = reorder(Description, neglog))) +
    geom_bar(stat = "identity", fill = color) +
    labs(x = "-log10(Adjusted p-value)",
         y = y_title,
         title = paste("Enriched", category, "Pathways")) +
    theme_minimal() +
    theme(
      axis.text.x = element_text(size = 12, face = "bold", colour = "black", angle = 45, hjust = 1),
      axis.text.y = element_text(size = 12, face = "bold", colour = "black"),
      axis.title.x = element_text(size = 14, face = "bold", colour = "black"),
      axis.title.y = element_text(size = 14, face = "bold", colour = "black"),
      plot.title = element_text(size = 14, face = "bold", colour = "black")
    )
  
  return(plot)
}

# Function for gProfiler Reactome & KEGG Analysis
process_gprofiler <- function(gene_set, background, category, color, y_title) {
  # Perform enrichment using gprofiler2
  enrichment <- gost(
    query = gene_set,
    organism = "hsapiens",
    user_threshold = 0.05,
    correction_method = "fdr",
    domain_scope = "custom",
    custom_bg = background,
    sources = category # Either "REAC" or "KEGG"
  )
  
  # Check if enrichment results exist
  if (is.null(enrichment$result) || nrow(enrichment$result) == 0) {
    message(paste("No significant enrichment found for", category, "in gProfiler"))
    return(NULL)
  }
  
  # Convert results to tibble and process top 20 terms
  enrichment_tibble <- enrichment$result %>%
    as_tibble() %>%
    mutate(Category = category,
           neglog = -log10(p_value)) %>%  # Compute -log10(p-value)
    arrange(desc(neglog)) %>%
    slice_head(n = min(20, nrow(.)))  # Ensure safe slicing
  
  # Generate plot
  plot <- ggplot(enrichment_tibble, aes(x = neglog, y = reorder(term_name, neglog))) +
    geom_bar(stat = "identity", fill = color) +
    labs(x = "-log10(p-value)",
         y = y_title,
         title = paste("Enriched", category, "Pathways")) +
    theme_minimal() +
    theme(
      axis.text.x = element_text(size = 12, face = "bold", colour = "black", angle = 45, hjust = 1),
      axis.text.y = element_text(size = 12, face = "bold", colour = "black"),
      axis.title.x = element_text(size = 14, face = "bold", colour = "black"),
      axis.title.y = element_text(size = 14, face = "bold", colour = "black"),
      plot.title = element_text(size = 14, face = "bold", colour = "black")
    )
  
  return(plot)
}

# Perform analysis for Reactome and KEGG using ClusterProfiler
cluster_reactome <- process_clusterProfiler(
  gene_set = prob_all_1,
  background = background,
  category = "Reactome",
  color = "#2E86C1",
  y_title = "Reactome Pathways"
)

cluster_kegg <- process_clusterProfiler(
  gene_set = prob_all_1,
  background = background,
  category = "KEGG",
  color = "#28B463",
  y_title = "KEGG Pathways"
)

# Combine Reactome and KEGG for ClusterProfiler
if (!is.null(cluster_reactome) && !is.null(cluster_kegg)) {
  cluster_combined <- cluster_reactome / cluster_kegg
} else if (!is.null(cluster_reactome)) {
  cluster_combined <- cluster_reactome
} else if (!is.null(cluster_kegg)) {
  cluster_combined <- cluster_kegg
} else {
  cluster_combined <- NULL
}

# Perform analysis for Reactome and KEGG using GProfiler
gprofiler_reactome <- process_gprofiler(
  gene_set = prob_all_1,
  background = background,
  category = "REAC",  # Corrected category for Reactome in gProfiler
  color = "#D35400",
  y_title = "Reactome Pathways"
)

gprofiler_kegg <- process_gprofiler(
  gene_set = prob_all_1,
  background = background,
  category = "KEGG",
  color = "#F39C12",
  y_title = "KEGG Pathways"
)

# Combine Reactome and KEGG for GProfiler
if (!is.null(gprofiler_reactome) && !is.null(gprofiler_kegg)) {
  gprofiler_combined <- gprofiler_reactome / gprofiler_kegg
} else if (!is.null(gprofiler_reactome)) {
  gprofiler_combined <- gprofiler_reactome
} else if (!is.null(gprofiler_kegg)) {
  gprofiler_combined <- gprofiler_kegg
} else {
  gprofiler_combined <- NULL
}

# Display plots (if they are not NULL)
if (!is.null(cluster_combined)) print(cluster_combined)

Version Author Date
fc2db42 sayanpaul01 2025-02-24
if (!is.null(gprofiler_combined)) print(gprofiler_combined)

Version Author Date
fc2db42 sayanpaul01 2025-02-24

📌 CX_DOX shared late response

📌 CX_DOX shared late response GO Enrichment Clusterprofiler

# Perform GO enrichment analysis for BP, MF, and CC
go_enrichment_BP <- enrichGO(gene = prob_all_2,
                             OrgDb = org.Hs.eg.db,
                             keyType = "ENTREZID",
                             universe = background,
                             ont = "BP",
                             pvalueCutoff = 0.05)

go_enrichment_MF <- enrichGO(gene = prob_all_2,
                             OrgDb = org.Hs.eg.db,
                             keyType = "ENTREZID",
                             universe = background,
                             ont = "MF",
                             pvalueCutoff = 0.05)

go_enrichment_CC <- enrichGO(gene = prob_all_2,
                             OrgDb = org.Hs.eg.db,
                             keyType = "ENTREZID",
                             universe = background,
                             ont = "CC",
                             pvalueCutoff = 0.05)

# Convert each enrichment result to a tibble, add a category column, and select top 20 terms
process_enrichment_tibble <- function(enrichment, category) {
  if (is.null(enrichment) || nrow(as.data.frame(enrichment)) == 0) {
    return(tibble(Description = "No enriched terms", neglog = 0, Category = category))
  } else {
    enrichment %>%
      as_tibble() %>%
      mutate(Category = category,
             neglog = -log(p.adjust)) %>% # Add -log(p.adjust) column
      arrange(desc(neglog)) %>%          # Sort by -log(p.adjust)
      slice(1:20)                        # Select top 20 terms
  }
}

BP_Tibble <- process_enrichment_tibble(go_enrichment_BP, "Biological Process")
MF_Tibble <- process_enrichment_tibble(go_enrichment_MF, "Molecular Function")
CC_Tibble <- process_enrichment_tibble(go_enrichment_CC, "Cellular Component")

# Combine all tibbles
combined_GO_Tibble <- bind_rows(BP_Tibble, MF_Tibble, CC_Tibble)
# Function to generate enrichment plots
process_enrichment_plot <- function(tibble, title, color) {
  ggplot(data = tibble, aes(x = neglog, y = reorder(Description, neglog))) +
    geom_bar(stat = "identity", fill = color) +
    labs(x = "-log(p-adjust)",
         y = title,
         title = paste("Top 20", title, "GO Terms")) +
    theme_minimal() +
    theme(
      axis.text.x = element_text(size = 12, face = "bold", colour = "black", angle = 45, hjust = 1),
      axis.text.y = element_text(size = 12, face = "bold", colour = "black"),
      axis.title.x = element_text(size = 14, face = "bold", colour = "black"),
      axis.title.y = element_text(size = 14, face = "bold", colour = "black"),
      plot.title = element_text(size = 14, face = "bold", colour = "black"),
      panel.border = element_rect(colour = "black", fill = NA, size = 0.3)
    ) +
    xlim(c(0, max(tibble$neglog) + 1))
}

# Generate separate plots
plot_BP <- process_enrichment_plot(BP_Tibble, "Biological Process", "#2E86C1")
plot_MF <- process_enrichment_plot(MF_Tibble, "Molecular Function", "#28B463")
plot_CC <- process_enrichment_plot(CC_Tibble, "Cellular Component", "#D35400")

# Combine the plots using patchwork
combined_plot <- plot_BP / plot_MF / plot_CC

# Display the combined plot
combined_plot

📌 CX_DOX shared late response GO Enrichment g:Profiler

# Load the gprofiler2 package
library(gprofiler2)
library(ggplot2)
library(dplyr)
library(patchwork)

# Perform GO enrichment analysis with gprofiler2
gost_results <- gost(
  query = prob_all_2,           # List of input genes (prob_all_2)
  organism = "hsapiens",   # Human organism
  user_threshold = 0.05,   # Adjusted p-value cutoff
  correction_method = "fdr", # Multiple testing correction
  domain_scope = "custom", # Use custom background
  custom_bg = background,    # Background set of genes
  sources = c("GO:BP", "GO:MF", "GO:CC") # Analyze GO categories
)

# Check if enrichment results exist
if (is.null(gost_results$result) || nrow(gost_results$result) == 0) {
  # If no enriched terms, create a placeholder dataframe
  combined_results <- tibble(
    term_name = "No enriched terms",
    p.adjust = NA,
    source = "N/A",
    Category = "N/A"
  )
} else {
  # Convert results to a data frame
  gost_results_df <- gost_results$result

  # Add a column for adjusted p-value
  gost_results_df <- gost_results_df %>%
    rename(p.adjust = p_value)

  # Separate results for BP, MF, and CC
  BP_results <- gost_results_df %>%
    filter(source == "GO:BP") %>%
    mutate(Category = "Biological Process")

  MF_results <- gost_results_df %>%
    filter(source == "GO:MF") %>%
    mutate(Category = "Molecular Function")

  CC_results <- gost_results_df %>%
    filter(source == "GO:CC") %>%
    mutate(Category = "Cellular Component")

  # Select the top 20 terms by adjusted p-value for each category
  top_BP <- BP_results %>%
    arrange(p.adjust) %>%
    slice_head(n = 20)

  top_MF <- MF_results %>%
    arrange(p.adjust) %>%
    slice_head(n = 20)

  top_CC <- CC_results %>%
    arrange(p.adjust) %>%
    slice_head(n = 20)

  # Combine all categories
  combined_results <- bind_rows(top_BP, top_MF, top_CC)
}

# Ensure all columns are atomic types for CSV export
combined_results_clean <- combined_results %>%
  mutate(across(everything(), ~ if (is.list(.)) sapply(., toString) else .))

# Function for plotting top terms
plot_gprofiler_results <- function(data, title, color) {
  ggplot(data, aes(x = -log10(p.adjust), y = reorder(term_name, -log10(p.adjust)))) +
    geom_bar(stat = "identity", fill = color) +
    labs(
      x = "-log10(Adjusted p-value)",
      y = title,
      title = paste("Top 20", title, "GO Terms")
    ) +
    theme_minimal() +
    theme(
      axis.text.x = element_text(size = 12, face = "bold", colour = "black", angle = 45, hjust = 1),
      axis.text.y = element_text(size = 12, face = "bold", colour = "black"),
      axis.title.x = element_text(size = 14, face = "bold", colour = "black"),
      axis.title.y = element_text(size = 14, face = "bold", colour = "black"),
      plot.title = element_text(size = 14, face = "bold", colour = "black"),
      panel.border = element_rect(colour = "black", fill = NA, size = 0.3)
    )
}

# Check if there are enrichment terms to plot
if (nrow(combined_results) == 1 && combined_results$term_name == "No enriched terms") {
  message("No enriched GO terms found for the input gene set.")
} else {
  # Plot the top 20 terms for each category
  plot_BP <- plot_gprofiler_results(top_BP, "Biological Process", "#2E86C1")
  plot_MF <- plot_gprofiler_results(top_MF, "Molecular Function", "#28B463")
  plot_CC <- plot_gprofiler_results(top_CC, "Cellular Component", "#D35400")

  # Combine the plots using patchwork
  combined_plot <- plot_BP / plot_MF / plot_CC

  # Display the combined plot
  combined_plot
}

📌 CX_DOX shared late response Pathway Enrichment

# Load required libraries
library(clusterProfiler)
library(org.Hs.eg.db) # Required for enrichPathway
library(gprofiler2)
library(ggplot2)
library(dplyr)
library(patchwork)
library(ReactomePA)

# Function for ClusterProfiler Reactome & KEGG Analysis
process_clusterProfiler <- function(gene_set, background, category, color, y_title) {
  # Perform enrichment based on the selected category
  if (category == "Reactome") {
    enrichment <- enrichPathway(
      gene = gene_set,
      organism = "human",
      pvalueCutoff = 0.05,
      pAdjustMethod = "BH",
      universe = background
    )
  } else if (category == "KEGG") {
    enrichment <- enrichKEGG(
      gene = gene_set,
      organism = "hsa",
      pvalueCutoff = 0.05,
      pAdjustMethod = "BH",
      universe = background
    )
  }
  
  # Check if enrichment results exist
  if (is.null(enrichment) || nrow(as.data.frame(enrichment)) == 0) {
    message(paste("No significant enrichment found for", category, "in ClusterProfiler"))
    return(NULL)
  }
  
  # Convert results to tibble and process top 20 terms
  enrichment_tibble <- as_tibble(as.data.frame(enrichment)) %>%
    mutate(Category = category,
           neglog = -log10(p.adjust)) %>%  # Compute -log10(p.adjust)
    arrange(desc(neglog)) %>%
    slice_head(n = min(20, nrow(.)))  # Ensure safe slicing
  
  # Generate plot
  plot <- ggplot(enrichment_tibble, aes(x = neglog, y = reorder(Description, neglog))) +
    geom_bar(stat = "identity", fill = color) +
    labs(x = "-log10(Adjusted p-value)",
         y = y_title,
         title = paste("Enriched", category, "Pathways")) +
    theme_minimal() +
    theme(
      axis.text.x = element_text(size = 12, face = "bold", colour = "black", angle = 45, hjust = 1),
      axis.text.y = element_text(size = 12, face = "bold", colour = "black"),
      axis.title.x = element_text(size = 14, face = "bold", colour = "black"),
      axis.title.y = element_text(size = 14, face = "bold", colour = "black"),
      plot.title = element_text(size = 14, face = "bold", colour = "black")
    )
  
  return(plot)
}

# Function for gProfiler Reactome & KEGG Analysis
process_gprofiler <- function(gene_set, background, category, color, y_title) {
  # Perform enrichment using gprofiler2
  enrichment <- gost(
    query = gene_set,
    organism = "hsapiens",
    user_threshold = 0.05,
    correction_method = "fdr",
    domain_scope = "custom",
    custom_bg = background,
    sources = category # Either "REAC" or "KEGG"
  )
  
  # Check if enrichment results exist
  if (is.null(enrichment$result) || nrow(enrichment$result) == 0) {
    message(paste("No significant enrichment found for", category, "in gProfiler"))
    return(NULL)
  }
  
  # Convert results to tibble and process top 20 terms
  enrichment_tibble <- enrichment$result %>%
    as_tibble() %>%
    mutate(Category = category,
           neglog = -log10(p_value)) %>%  # Compute -log10(p-value)
    arrange(desc(neglog)) %>%
    slice_head(n = min(20, nrow(.)))  # Ensure safe slicing
  
  # Generate plot
  plot <- ggplot(enrichment_tibble, aes(x = neglog, y = reorder(term_name, neglog))) +
    geom_bar(stat = "identity", fill = color) +
    labs(x = "-log10(p-value)",
         y = y_title,
         title = paste("Enriched", category, "Pathways")) +
    theme_minimal() +
    theme(
      axis.text.x = element_text(size = 12, face = "bold", colour = "black", angle = 45, hjust = 1),
      axis.text.y = element_text(size = 12, face = "bold", colour = "black"),
      axis.title.x = element_text(size = 14, face = "bold", colour = "black"),
      axis.title.y = element_text(size = 14, face = "bold", colour = "black"),
      plot.title = element_text(size = 14, face = "bold", colour = "black")
    )
  
  return(plot)
}

# Perform analysis for Reactome and KEGG using ClusterProfiler
cluster_reactome <- process_clusterProfiler(
  gene_set = prob_all_2,
  background = background,
  category = "Reactome",
  color = "#2E86C1",
  y_title = "Reactome Pathways"
)

cluster_kegg <- process_clusterProfiler(
  gene_set = prob_all_2,
  background = background,
  category = "KEGG",
  color = "#28B463",
  y_title = "KEGG Pathways"
)

# Combine Reactome and KEGG for ClusterProfiler
if (!is.null(cluster_reactome) && !is.null(cluster_kegg)) {
  cluster_combined <- cluster_reactome / cluster_kegg
} else if (!is.null(cluster_reactome)) {
  cluster_combined <- cluster_reactome
} else if (!is.null(cluster_kegg)) {
  cluster_combined <- cluster_kegg
} else {
  cluster_combined <- NULL
}

# Perform analysis for Reactome and KEGG using GProfiler
gprofiler_reactome <- process_gprofiler(
  gene_set = prob_all_2,
  background = background,
  category = "REAC",  # Corrected category for Reactome in gProfiler
  color = "#D35400",
  y_title = "Reactome Pathways"
)

gprofiler_kegg <- process_gprofiler(
  gene_set = prob_all_2,
  background = background,
  category = "KEGG",
  color = "#F39C12",
  y_title = "KEGG Pathways"
)

# Combine Reactome and KEGG for GProfiler
if (!is.null(gprofiler_reactome) && !is.null(gprofiler_kegg)) {
  gprofiler_combined <- gprofiler_reactome / gprofiler_kegg
} else if (!is.null(gprofiler_reactome)) {
  gprofiler_combined <- gprofiler_reactome
} else if (!is.null(gprofiler_kegg)) {
  gprofiler_combined <- gprofiler_kegg
} else {
  gprofiler_combined <- NULL
}

# Display plots (if they are not NULL)
if (!is.null(cluster_combined)) print(cluster_combined)

if (!is.null(gprofiler_combined)) print(gprofiler_combined)

📌 DOX-specific response

📌 DOX-specific response GO Enrichment Clusterprofiler

# Perform GO enrichment analysis for BP, MF, and CC
go_enrichment_BP <- enrichGO(gene = prob_all_3,
                             OrgDb = org.Hs.eg.db,
                             keyType = "ENTREZID",
                             universe = background,
                             ont = "BP",
                             pvalueCutoff = 0.05)

go_enrichment_MF <- enrichGO(gene = prob_all_3,
                             OrgDb = org.Hs.eg.db,
                             keyType = "ENTREZID",
                             universe = background,
                             ont = "MF",
                             pvalueCutoff = 0.05)

go_enrichment_CC <- enrichGO(gene = prob_all_3,
                             OrgDb = org.Hs.eg.db,
                             keyType = "ENTREZID",
                             universe = background,
                             ont = "CC",
                             pvalueCutoff = 0.05)

# Convert each enrichment result to a tibble, add a category column, and select top 20 terms
process_enrichment_tibble <- function(enrichment, category) {
  if (is.null(enrichment) || nrow(as.data.frame(enrichment)) == 0) {
    return(tibble(Description = "No enriched terms", neglog = 0, Category = category))
  } else {
    enrichment %>%
      as_tibble() %>%
      mutate(Category = category,
             neglog = -log(p.adjust)) %>% # Add -log(p.adjust) column
      arrange(desc(neglog)) %>%          # Sort by -log(p.adjust)
      slice(1:20)                        # Select top 20 terms
  }
}

BP_Tibble <- process_enrichment_tibble(go_enrichment_BP, "Biological Process")
MF_Tibble <- process_enrichment_tibble(go_enrichment_MF, "Molecular Function")
CC_Tibble <- process_enrichment_tibble(go_enrichment_CC, "Cellular Component")

# Combine all tibbles
combined_GO_Tibble <- bind_rows(BP_Tibble, MF_Tibble, CC_Tibble)
# Function to generate enrichment plots
process_enrichment_plot <- function(tibble, title, color) {
  ggplot(data = tibble, aes(x = neglog, y = reorder(Description, neglog))) +
    geom_bar(stat = "identity", fill = color) +
    labs(x = "-log(p-adjust)",
         y = title,
         title = paste("Top 20", title, "GO Terms")) +
    theme_minimal() +
    theme(
      axis.text.x = element_text(size = 12, face = "bold", colour = "black", angle = 45, hjust = 1),
      axis.text.y = element_text(size = 12, face = "bold", colour = "black"),
      axis.title.x = element_text(size = 14, face = "bold", colour = "black"),
      axis.title.y = element_text(size = 14, face = "bold", colour = "black"),
      plot.title = element_text(size = 14, face = "bold", colour = "black"),
      panel.border = element_rect(colour = "black", fill = NA, size = 0.3)
    ) +
    xlim(c(0, max(tibble$neglog) + 1))
}

# Generate separate plots
plot_BP <- process_enrichment_plot(BP_Tibble, "Biological Process", "#2E86C1")
plot_MF <- process_enrichment_plot(MF_Tibble, "Molecular Function", "#28B463")
plot_CC <- process_enrichment_plot(CC_Tibble, "Cellular Component", "#D35400")

# Combine the plots using patchwork
combined_plot <- plot_BP / plot_MF / plot_CC

# Display the combined plot
combined_plot

📌 DOX-specific response GO Enrichment g:Profiler

# Load the gprofiler2 package
library(gprofiler2)
library(ggplot2)
library(dplyr)
library(patchwork)

# Perform GO enrichment analysis with gprofiler2
gost_results <- gost(
  query = prob_all_3,           # List of input genes (prob_all_3)
  organism = "hsapiens",   # Human organism
  user_threshold = 0.05,   # Adjusted p-value cutoff
  correction_method = "fdr", # Multiple testing correction
  domain_scope = "custom", # Use custom background
  custom_bg = background,    # Background set of genes
  sources = c("GO:BP", "GO:MF", "GO:CC") # Analyze GO categories
)

# Check if enrichment results exist
if (is.null(gost_results$result) || nrow(gost_results$result) == 0) {
  # If no enriched terms, create a placeholder dataframe
  combined_results <- tibble(
    term_name = "No enriched terms",
    p.adjust = NA,
    source = "N/A",
    Category = "N/A"
  )
} else {
  # Convert results to a data frame
  gost_results_df <- gost_results$result

  # Add a column for adjusted p-value
  gost_results_df <- gost_results_df %>%
    rename(p.adjust = p_value)

  # Separate results for BP, MF, and CC
  BP_results <- gost_results_df %>%
    filter(source == "GO:BP") %>%
    mutate(Category = "Biological Process")

  MF_results <- gost_results_df %>%
    filter(source == "GO:MF") %>%
    mutate(Category = "Molecular Function")

  CC_results <- gost_results_df %>%
    filter(source == "GO:CC") %>%
    mutate(Category = "Cellular Component")

  # Select the top 20 terms by adjusted p-value for each category
  top_BP <- BP_results %>%
    arrange(p.adjust) %>%
    slice_head(n = 20)

  top_MF <- MF_results %>%
    arrange(p.adjust) %>%
    slice_head(n = 20)

  top_CC <- CC_results %>%
    arrange(p.adjust) %>%
    slice_head(n = 20)

  # Combine all categories
  combined_results <- bind_rows(top_BP, top_MF, top_CC)
}

# Ensure all columns are atomic types for CSV export
combined_results_clean <- combined_results %>%
  mutate(across(everything(), ~ if (is.list(.)) sapply(., toString) else .))

# Function for plotting top terms
plot_gprofiler_results <- function(data, title, color) {
  ggplot(data, aes(x = -log10(p.adjust), y = reorder(term_name, -log10(p.adjust)))) +
    geom_bar(stat = "identity", fill = color) +
    labs(
      x = "-log10(Adjusted p-value)",
      y = title,
      title = paste("Top 20", title, "GO Terms")
    ) +
    theme_minimal() +
    theme(
      axis.text.x = element_text(size = 12, face = "bold", colour = "black", angle = 45, hjust = 1),
      axis.text.y = element_text(size = 12, face = "bold", colour = "black"),
      axis.title.x = element_text(size = 14, face = "bold", colour = "black"),
      axis.title.y = element_text(size = 14, face = "bold", colour = "black"),
      plot.title = element_text(size = 14, face = "bold", colour = "black"),
      panel.border = element_rect(colour = "black", fill = NA, size = 0.3)
    )
}

# Check if there are enrichment terms to plot
if (nrow(combined_results) == 1 && combined_results$term_name == "No enriched terms") {
  message("No enriched GO terms found for the input gene set.")
} else {
  # Plot the top 20 terms for each category
  plot_BP <- plot_gprofiler_results(top_BP, "Biological Process", "#2E86C1")
  plot_MF <- plot_gprofiler_results(top_MF, "Molecular Function", "#28B463")
  plot_CC <- plot_gprofiler_results(top_CC, "Cellular Component", "#D35400")

  # Combine the plots using patchwork
  combined_plot <- plot_BP / plot_MF / plot_CC

  # Display the combined plot
  combined_plot
}

📌 DOX-specific response Pathway Enrichment

# Load required libraries
library(clusterProfiler)
library(org.Hs.eg.db) # Required for enrichPathway
library(gprofiler2)
library(ggplot2)
library(dplyr)
library(patchwork)
library(ReactomePA)

# Function for ClusterProfiler Reactome & KEGG Analysis
process_clusterProfiler <- function(gene_set, background, category, color, y_title) {
  # Perform enrichment based on the selected category
  if (category == "Reactome") {
    enrichment <- enrichPathway(
      gene = gene_set,
      organism = "human",
      pvalueCutoff = 0.05,
      pAdjustMethod = "BH",
      universe = background
    )
  } else if (category == "KEGG") {
    enrichment <- enrichKEGG(
      gene = gene_set,
      organism = "hsa",
      pvalueCutoff = 0.05,
      pAdjustMethod = "BH",
      universe = background
    )
  }
  
  # Check if enrichment results exist
  if (is.null(enrichment) || nrow(as.data.frame(enrichment)) == 0) {
    message(paste("No significant enrichment found for", category, "in ClusterProfiler"))
    return(NULL)
  }
  
  # Convert results to tibble and process top 20 terms
  enrichment_tibble <- as_tibble(as.data.frame(enrichment)) %>%
    mutate(Category = category,
           neglog = -log10(p.adjust)) %>%  # Compute -log10(p.adjust)
    arrange(desc(neglog)) %>%
    slice_head(n = min(20, nrow(.)))  # Ensure safe slicing
  
  # Generate plot
  plot <- ggplot(enrichment_tibble, aes(x = neglog, y = reorder(Description, neglog))) +
    geom_bar(stat = "identity", fill = color) +
    labs(x = "-log10(Adjusted p-value)",
         y = y_title,
         title = paste("Enriched", category, "Pathways")) +
    theme_minimal() +
    theme(
      axis.text.x = element_text(size = 12, face = "bold", colour = "black", angle = 45, hjust = 1),
      axis.text.y = element_text(size = 12, face = "bold", colour = "black"),
      axis.title.x = element_text(size = 14, face = "bold", colour = "black"),
      axis.title.y = element_text(size = 14, face = "bold", colour = "black"),
      plot.title = element_text(size = 14, face = "bold", colour = "black")
    )
  
  return(plot)
}

# Function for gProfiler Reactome & KEGG Analysis
process_gprofiler <- function(gene_set, background, category, color, y_title) {
  # Perform enrichment using gprofiler2
  enrichment <- gost(
    query = gene_set,
    organism = "hsapiens",
    user_threshold = 0.05,
    correction_method = "fdr",
    domain_scope = "custom",
    custom_bg = background,
    sources = category # Either "REAC" or "KEGG"
  )
  
  # Check if enrichment results exist
  if (is.null(enrichment$result) || nrow(enrichment$result) == 0) {
    message(paste("No significant enrichment found for", category, "in gProfiler"))
    return(NULL)
  }
  
  # Convert results to tibble and process top 20 terms
  enrichment_tibble <- enrichment$result %>%
    as_tibble() %>%
    mutate(Category = category,
           neglog = -log10(p_value)) %>%  # Compute -log10(p-value)
    arrange(desc(neglog)) %>%
    slice_head(n = min(20, nrow(.)))  # Ensure safe slicing
  
  # Generate plot
  plot <- ggplot(enrichment_tibble, aes(x = neglog, y = reorder(term_name, neglog))) +
    geom_bar(stat = "identity", fill = color) +
    labs(x = "-log10(p-value)",
         y = y_title,
         title = paste("Enriched", category, "Pathways")) +
    theme_minimal() +
    theme(
      axis.text.x = element_text(size = 12, face = "bold", colour = "black", angle = 45, hjust = 1),
      axis.text.y = element_text(size = 12, face = "bold", colour = "black"),
      axis.title.x = element_text(size = 14, face = "bold", colour = "black"),
      axis.title.y = element_text(size = 14, face = "bold", colour = "black"),
      plot.title = element_text(size = 14, face = "bold", colour = "black")
    )
  
  return(plot)
}

# Perform analysis for Reactome and KEGG using ClusterProfiler
cluster_reactome <- process_clusterProfiler(
  gene_set = prob_all_3,
  background = background,
  category = "Reactome",
  color = "#2E86C1",
  y_title = "Reactome Pathways"
)

cluster_kegg <- process_clusterProfiler(
  gene_set = prob_all_3,
  background = background,
  category = "KEGG",
  color = "#28B463",
  y_title = "KEGG Pathways"
)

# Combine Reactome and KEGG for ClusterProfiler
if (!is.null(cluster_reactome) && !is.null(cluster_kegg)) {
  cluster_combined <- cluster_reactome / cluster_kegg
} else if (!is.null(cluster_reactome)) {
  cluster_combined <- cluster_reactome
} else if (!is.null(cluster_kegg)) {
  cluster_combined <- cluster_kegg
} else {
  cluster_combined <- NULL
}

# Perform analysis for Reactome and KEGG using GProfiler
gprofiler_reactome <- process_gprofiler(
  gene_set = prob_all_3,
  background = background,
  category = "REAC",  # Corrected category for Reactome in gProfiler
  color = "#D35400",
  y_title = "Reactome Pathways"
)

gprofiler_kegg <- process_gprofiler(
  gene_set = prob_all_3,
  background = background,
  category = "KEGG",
  color = "#F39C12",
  y_title = "KEGG Pathways"
)

# Combine Reactome and KEGG for GProfiler
if (!is.null(gprofiler_reactome) && !is.null(gprofiler_kegg)) {
  gprofiler_combined <- gprofiler_reactome / gprofiler_kegg
} else if (!is.null(gprofiler_reactome)) {
  gprofiler_combined <- gprofiler_reactome
} else if (!is.null(gprofiler_kegg)) {
  gprofiler_combined <- gprofiler_kegg
} else {
  gprofiler_combined <- NULL
}

# Display plots (if they are not NULL)
if (!is.null(cluster_combined)) print(cluster_combined)

if (!is.null(gprofiler_combined)) print(gprofiler_combined)

📌 Late high dose DOX-specific response

📌 Late high dose DOX-specific response GO Enrichment Clusterprofiler

# Perform GO enrichment analysis for BP, MF, and CC
go_enrichment_BP <- enrichGO(gene = prob_all_4,
                             OrgDb = org.Hs.eg.db,
                             keyType = "ENTREZID",
                             universe = background,
                             ont = "BP",
                             pvalueCutoff = 0.05)

go_enrichment_MF <- enrichGO(gene = prob_all_4,
                             OrgDb = org.Hs.eg.db,
                             keyType = "ENTREZID",
                             universe = background,
                             ont = "MF",
                             pvalueCutoff = 0.05)

go_enrichment_CC <- enrichGO(gene = prob_all_4,
                             OrgDb = org.Hs.eg.db,
                             keyType = "ENTREZID",
                             universe = background,
                             ont = "CC",
                             pvalueCutoff = 0.05)

# Convert each enrichment result to a tibble, add a category column, and select top 20 terms
process_enrichment_tibble <- function(enrichment, category) {
  if (is.null(enrichment) || nrow(as.data.frame(enrichment)) == 0) {
    return(tibble(Description = "No enriched terms", neglog = 0, Category = category))
  } else {
    enrichment %>%
      as_tibble() %>%
      mutate(Category = category,
             neglog = -log(p.adjust)) %>% # Add -log(p.adjust) column
      arrange(desc(neglog)) %>%          # Sort by -log(p.adjust)
      slice(1:20)                        # Select top 20 terms
  }
}

BP_Tibble <- process_enrichment_tibble(go_enrichment_BP, "Biological Process")
MF_Tibble <- process_enrichment_tibble(go_enrichment_MF, "Molecular Function")
CC_Tibble <- process_enrichment_tibble(go_enrichment_CC, "Cellular Component")

# Combine all tibbles
combined_GO_Tibble <- bind_rows(BP_Tibble, MF_Tibble, CC_Tibble)
# Function to generate enrichment plots
process_enrichment_plot <- function(tibble, title, color) {
  ggplot(data = tibble, aes(x = neglog, y = reorder(Description, neglog))) +
    geom_bar(stat = "identity", fill = color) +
    labs(x = "-log(p-adjust)",
         y = title,
         title = paste("Top 20", title, "GO Terms")) +
    theme_minimal() +
    theme(
      axis.text.x = element_text(size = 12, face = "bold", colour = "black", angle = 45, hjust = 1),
      axis.text.y = element_text(size = 12, face = "bold", colour = "black"),
      axis.title.x = element_text(size = 14, face = "bold", colour = "black"),
      axis.title.y = element_text(size = 14, face = "bold", colour = "black"),
      plot.title = element_text(size = 14, face = "bold", colour = "black"),
      panel.border = element_rect(colour = "black", fill = NA, size = 0.3)
    ) +
    xlim(c(0, max(tibble$neglog) + 1))
}

# Generate separate plots
plot_BP <- process_enrichment_plot(BP_Tibble, "Biological Process", "#2E86C1")
plot_MF <- process_enrichment_plot(MF_Tibble, "Molecular Function", "#28B463")
plot_CC <- process_enrichment_plot(CC_Tibble, "Cellular Component", "#D35400")

# Combine the plots using patchwork
combined_plot <- plot_BP / plot_MF / plot_CC

# Display the combined plot
combined_plot

📌 Late high dose DOX-specific response GO Enrichment g:Profiler

# Load the gprofiler2 package
library(gprofiler2)
library(ggplot2)
library(dplyr)
library(patchwork)

# Perform GO enrichment analysis with gprofiler2
gost_results <- gost(
  query = prob_all_4,           # List of input genes (prob_all_4)
  organism = "hsapiens",   # Human organism
  user_threshold = 0.05,   # Adjusted p-value cutoff
  correction_method = "fdr", # Multiple testing correction
  domain_scope = "custom", # Use custom background
  custom_bg = background,    # Background set of genes
  sources = c("GO:BP", "GO:MF", "GO:CC") # Analyze GO categories
)

# Check if enrichment results exist
if (is.null(gost_results$result) || nrow(gost_results$result) == 0) {
  # If no enriched terms, create a placeholder dataframe
  combined_results <- tibble(
    term_name = "No enriched terms",
    p.adjust = NA,
    source = "N/A",
    Category = "N/A"
  )
} else {
  # Convert results to a data frame
  gost_results_df <- gost_results$result

  # Add a column for adjusted p-value
  gost_results_df <- gost_results_df %>%
    rename(p.adjust = p_value)

  # Separate results for BP, MF, and CC
  BP_results <- gost_results_df %>%
    filter(source == "GO:BP") %>%
    mutate(Category = "Biological Process")

  MF_results <- gost_results_df %>%
    filter(source == "GO:MF") %>%
    mutate(Category = "Molecular Function")

  CC_results <- gost_results_df %>%
    filter(source == "GO:CC") %>%
    mutate(Category = "Cellular Component")

  # Select the top 20 terms by adjusted p-value for each category
  top_BP <- BP_results %>%
    arrange(p.adjust) %>%
    slice_head(n = 20)

  top_MF <- MF_results %>%
    arrange(p.adjust) %>%
    slice_head(n = 20)

  top_CC <- CC_results %>%
    arrange(p.adjust) %>%
    slice_head(n = 20)

  # Combine all categories
  combined_results <- bind_rows(top_BP, top_MF, top_CC)
}

# Ensure all columns are atomic types for CSV export
combined_results_clean <- combined_results %>%
  mutate(across(everything(), ~ if (is.list(.)) sapply(., toString) else .))

# Function for plotting top terms
plot_gprofiler_results <- function(data, title, color) {
  ggplot(data, aes(x = -log10(p.adjust), y = reorder(term_name, -log10(p.adjust)))) +
    geom_bar(stat = "identity", fill = color) +
    labs(
      x = "-log10(Adjusted p-value)",
      y = title,
      title = paste("Top 20", title, "GO Terms")
    ) +
    theme_minimal() +
    theme(
      axis.text.x = element_text(size = 12, face = "bold", colour = "black", angle = 45, hjust = 1),
      axis.text.y = element_text(size = 12, face = "bold", colour = "black"),
      axis.title.x = element_text(size = 14, face = "bold", colour = "black"),
      axis.title.y = element_text(size = 14, face = "bold", colour = "black"),
      plot.title = element_text(size = 14, face = "bold", colour = "black"),
      panel.border = element_rect(colour = "black", fill = NA, size = 0.3)
    )
}

# Check if there are enrichment terms to plot
if (nrow(combined_results) == 1 && combined_results$term_name == "No enriched terms") {
  message("No enriched GO terms found for the input gene set.")
} else {
  # Plot the top 20 terms for each category
  plot_BP <- plot_gprofiler_results(top_BP, "Biological Process", "#2E86C1")
  plot_MF <- plot_gprofiler_results(top_MF, "Molecular Function", "#28B463")
  plot_CC <- plot_gprofiler_results(top_CC, "Cellular Component", "#D35400")

  # Combine the plots using patchwork
  combined_plot <- plot_BP / plot_MF / plot_CC

  # Display the combined plot
  combined_plot
}

📌 Late high dose DOX-specific response Pathway Enrichment

# Load required libraries
library(clusterProfiler)
library(org.Hs.eg.db) # Required for enrichPathway
library(gprofiler2)
library(ggplot2)
library(dplyr)
library(patchwork)
library(ReactomePA)

# Function for ClusterProfiler Reactome & KEGG Analysis
process_clusterProfiler <- function(gene_set, background, category, color, y_title) {
  # Perform enrichment based on the selected category
  if (category == "Reactome") {
    enrichment <- enrichPathway(
      gene = gene_set,
      organism = "human",
      pvalueCutoff = 0.05,
      pAdjustMethod = "BH",
      universe = background
    )
  } else if (category == "KEGG") {
    enrichment <- enrichKEGG(
      gene = gene_set,
      organism = "hsa",
      pvalueCutoff = 0.05,
      pAdjustMethod = "BH",
      universe = background
    )
  }
  
  # Check if enrichment results exist
  if (is.null(enrichment) || nrow(as.data.frame(enrichment)) == 0) {
    message(paste("No significant enrichment found for", category, "in ClusterProfiler"))
    return(NULL)
  }
  
  # Convert results to tibble and process top 20 terms
  enrichment_tibble <- as_tibble(as.data.frame(enrichment)) %>%
    mutate(Category = category,
           neglog = -log10(p.adjust)) %>%  # Compute -log10(p.adjust)
    arrange(desc(neglog)) %>%
    slice_head(n = min(20, nrow(.)))  # Ensure safe slicing
  
  # Generate plot
  plot <- ggplot(enrichment_tibble, aes(x = neglog, y = reorder(Description, neglog))) +
    geom_bar(stat = "identity", fill = color) +
    labs(x = "-log10(Adjusted p-value)",
         y = y_title,
         title = paste("Enriched", category, "Pathways")) +
    theme_minimal() +
    theme(
      axis.text.x = element_text(size = 12, face = "bold", colour = "black", angle = 45, hjust = 1),
      axis.text.y = element_text(size = 12, face = "bold", colour = "black"),
      axis.title.x = element_text(size = 14, face = "bold", colour = "black"),
      axis.title.y = element_text(size = 14, face = "bold", colour = "black"),
      plot.title = element_text(size = 14, face = "bold", colour = "black")
    )
  
  return(plot)
}

# Function for gProfiler Reactome & KEGG Analysis
process_gprofiler <- function(gene_set, background, category, color, y_title) {
  # Perform enrichment using gprofiler2
  enrichment <- gost(
    query = gene_set,
    organism = "hsapiens",
    user_threshold = 0.05,
    correction_method = "fdr",
    domain_scope = "custom",
    custom_bg = background,
    sources = category # Either "REAC" or "KEGG"
  )
  
  # Check if enrichment results exist
  if (is.null(enrichment$result) || nrow(enrichment$result) == 0) {
    message(paste("No significant enrichment found for", category, "in gProfiler"))
    return(NULL)
  }
  
  # Convert results to tibble and process top 20 terms
  enrichment_tibble <- enrichment$result %>%
    as_tibble() %>%
    mutate(Category = category,
           neglog = -log10(p_value)) %>%  # Compute -log10(p-value)
    arrange(desc(neglog)) %>%
    slice_head(n = min(20, nrow(.)))  # Ensure safe slicing
  
  # Generate plot
  plot <- ggplot(enrichment_tibble, aes(x = neglog, y = reorder(term_name, neglog))) +
    geom_bar(stat = "identity", fill = color) +
    labs(x = "-log10(p-value)",
         y = y_title,
         title = paste("Enriched", category, "Pathways")) +
    theme_minimal() +
    theme(
      axis.text.x = element_text(size = 12, face = "bold", colour = "black", angle = 45, hjust = 1),
      axis.text.y = element_text(size = 12, face = "bold", colour = "black"),
      axis.title.x = element_text(size = 14, face = "bold", colour = "black"),
      axis.title.y = element_text(size = 14, face = "bold", colour = "black"),
      plot.title = element_text(size = 14, face = "bold", colour = "black")
    )
  
  return(plot)
}

# Perform analysis for Reactome and KEGG using ClusterProfiler
cluster_reactome <- process_clusterProfiler(
  gene_set = prob_all_4,
  background = background,
  category = "Reactome",
  color = "#2E86C1",
  y_title = "Reactome Pathways"
)

cluster_kegg <- process_clusterProfiler(
  gene_set = prob_all_4,
  background = background,
  category = "KEGG",
  color = "#28B463",
  y_title = "KEGG Pathways"
)

# Combine Reactome and KEGG for ClusterProfiler
if (!is.null(cluster_reactome) && !is.null(cluster_kegg)) {
  cluster_combined <- cluster_reactome / cluster_kegg
} else if (!is.null(cluster_reactome)) {
  cluster_combined <- cluster_reactome
} else if (!is.null(cluster_kegg)) {
  cluster_combined <- cluster_kegg
} else {
  cluster_combined <- NULL
}

# Perform analysis for Reactome and KEGG using GProfiler
gprofiler_reactome <- process_gprofiler(
  gene_set = prob_all_4,
  background = background,
  category = "REAC",  # Corrected category for Reactome in gProfiler
  color = "#D35400",
  y_title = "Reactome Pathways"
)

gprofiler_kegg <- process_gprofiler(
  gene_set = prob_all_4,
  background = background,
  category = "KEGG",
  color = "#F39C12",
  y_title = "KEGG Pathways"
)

# Combine Reactome and KEGG for GProfiler
if (!is.null(gprofiler_reactome) && !is.null(gprofiler_kegg)) {
  gprofiler_combined <- gprofiler_reactome / gprofiler_kegg
} else if (!is.null(gprofiler_reactome)) {
  gprofiler_combined <- gprofiler_reactome
} else if (!is.null(gprofiler_kegg)) {
  gprofiler_combined <- gprofiler_kegg
} else {
  gprofiler_combined <- NULL
}

# Display plots (if they are not NULL)
if (!is.null(cluster_combined)) print(cluster_combined)
if (!is.null(gprofiler_combined)) print(gprofiler_combined)

sessionInfo()
R version 4.3.0 (2023-04-21 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 11 x64 (build 22631)

Matrix products: default


locale:
[1] LC_COLLATE=English_United States.utf8 
[2] LC_CTYPE=English_United States.utf8   
[3] LC_MONETARY=English_United States.utf8
[4] LC_NUMERIC=C                          
[5] LC_TIME=English_United States.utf8    

time zone: America/Chicago
tzcode source: internal

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

other attached packages:
 [1] ReactomePA_1.46.0                       
 [2] patchwork_1.3.0                         
 [3] gprofiler2_0.2.3                        
 [4] DOSE_3.28.2                             
 [5] TxDb.Hsapiens.UCSC.hg38.knownGene_3.18.0
 [6] RColorBrewer_1.1-3                      
 [7] clusterProfiler_4.10.1                  
 [8] pheatmap_1.0.12                         
 [9] qvalue_2.34.0                           
[10] BiocParallel_1.36.0                     
[11] Homo.sapiens_1.3.1                      
[12] TxDb.Hsapiens.UCSC.hg19.knownGene_3.2.2 
[13] org.Hs.eg.db_3.18.0                     
[14] GO.db_3.18.0                            
[15] OrganismDbi_1.44.0                      
[16] GenomicFeatures_1.54.4                  
[17] GenomicRanges_1.54.1                    
[18] GenomeInfoDb_1.38.8                     
[19] AnnotationDbi_1.64.1                    
[20] IRanges_2.36.0                          
[21] S4Vectors_0.40.1                        
[22] Biobase_2.62.0                          
[23] BiocGenerics_0.48.1                     
[24] edgeR_4.0.1                             
[25] limma_3.58.1                            
[26] cluster_2.1.6                           
[27] ggfortify_0.4.17                        
[28] lubridate_1.9.3                         
[29] forcats_1.0.0                           
[30] stringr_1.5.1                           
[31] dplyr_1.1.4                             
[32] purrr_1.0.2                             
[33] readr_2.1.5                             
[34] tidyr_1.3.1                             
[35] tibble_3.2.1                            
[36] ggplot2_3.5.1                           
[37] tidyverse_2.0.0                         

loaded via a namespace (and not attached):
  [1] splines_4.3.0               later_1.3.2                
  [3] BiocIO_1.12.0               bitops_1.0-7               
  [5] ggplotify_0.1.2             filelock_1.0.3             
  [7] polyclip_1.10-7             graph_1.80.0               
  [9] XML_3.99-0.17               lifecycle_1.0.4            
 [11] rprojroot_2.0.4             lattice_0.22-5             
 [13] MASS_7.3-60                 magrittr_2.0.3             
 [15] plotly_4.10.4               sass_0.4.9                 
 [17] rmarkdown_2.29              jquerylib_0.1.4            
 [19] yaml_2.3.10                 httpuv_1.6.15              
 [21] cowplot_1.1.3               DBI_1.2.3                  
 [23] abind_1.4-8                 zlibbioc_1.48.0            
 [25] ggraph_2.2.1                RCurl_1.98-1.13            
 [27] yulab.utils_0.1.8           tweenr_2.0.3               
 [29] rappdirs_0.3.3              git2r_0.35.0               
 [31] GenomeInfoDbData_1.2.11     enrichplot_1.22.0          
 [33] ggrepel_0.9.6               tidytree_0.4.6             
 [35] reactome.db_1.86.2          codetools_0.2-20           
 [37] DelayedArray_0.28.0         xml2_1.3.6                 
 [39] ggforce_0.4.2               tidyselect_1.2.1           
 [41] aplot_0.2.3                 farver_2.1.2               
 [43] viridis_0.6.5               matrixStats_1.4.1          
 [45] BiocFileCache_2.10.2        GenomicAlignments_1.38.2   
 [47] jsonlite_1.8.9              tidygraph_1.3.1            
 [49] tools_4.3.0                 progress_1.2.3             
 [51] treeio_1.26.0               Rcpp_1.0.12                
 [53] glue_1.7.0                  gridExtra_2.3              
 [55] SparseArray_1.2.4           xfun_0.50                  
 [57] MatrixGenerics_1.14.0       withr_3.0.2                
 [59] BiocManager_1.30.25         fastmap_1.1.1              
 [61] digest_0.6.34               timechange_0.3.0           
 [63] R6_2.5.1                    gridGraphics_0.5-1         
 [65] colorspace_2.1-0            biomaRt_2.58.2             
 [67] RSQLite_2.3.3               generics_0.1.3             
 [69] data.table_1.14.10          rtracklayer_1.62.0         
 [71] htmlwidgets_1.6.4           prettyunits_1.2.0          
 [73] graphlayouts_1.2.0          httr_1.4.7                 
 [75] S4Arrays_1.2.1              scatterpie_0.2.4           
 [77] graphite_1.48.0             whisker_0.4.1              
 [79] pkgconfig_2.0.3             gtable_0.3.6               
 [81] blob_1.2.4                  workflowr_1.7.1            
 [83] XVector_0.42.0              shadowtext_0.1.4           
 [85] htmltools_0.5.8.1           fgsea_1.28.0               
 [87] RBGL_1.78.0                 scales_1.3.0               
 [89] png_0.1-8                   ggfun_0.1.8                
 [91] knitr_1.49                  rstudioapi_0.17.1          
 [93] tzdb_0.4.0                  reshape2_1.4.4             
 [95] rjson_0.2.23                nlme_3.1-166               
 [97] curl_6.0.1                  cachem_1.0.8               
 [99] parallel_4.3.0              HDO.db_0.99.1              
[101] restfulr_0.0.15             pillar_1.10.1              
[103] grid_4.3.0                  vctrs_0.6.5                
[105] promises_1.3.0              dbplyr_2.5.0               
[107] evaluate_1.0.3              cli_3.6.1                  
[109] locfit_1.5-9.8              compiler_4.3.0             
[111] Rsamtools_2.18.0            rlang_1.1.3                
[113] crayon_1.5.3                labeling_0.4.3             
[115] plyr_1.8.9                  fs_1.6.3                   
[117] stringi_1.8.3               viridisLite_0.4.2          
[119] munsell_0.5.1               Biostrings_2.70.1          
[121] lazyeval_0.2.2              GOSemSim_2.28.1            
[123] Matrix_1.6-1.1              hms_1.1.3                  
[125] bit64_4.0.5                 KEGGREST_1.42.0            
[127] statmod_1.5.0               SummarizedExperiment_1.32.0
[129] igraph_2.1.1                memoise_2.0.1              
[131] bslib_0.8.0                 ggtree_3.10.1              
[133] fastmatch_1.1-4             bit_4.0.5                  
[135] gson_0.1.0                  ape_5.8