ubigen/scripts/gsea.R

60 lines
1.7 KiB
R
Raw Normal View History

# This script performs a gene set enrichment analysis (GSEA) across the whole
# ranking of ubiquituos genes using g:Profiler.
# Size of each gene bucket. The GSEA is done once for each bucket within the
# ranking.
bucket_size <- 500
library(data.table)
library(here)
i_am("scripts/gsea.R")
file_path <- here("scripts", "output", "ubigen_gsea.Rds")
image_path <- here("scripts", "output", "ubigen_gsea.svg")
# The result will be saved in `file_path` to avoid unnecessary API calls.
result <- if (file.exists(file_path)) {
readRDS(file_path)
} else {
data <- copy(ubigen::genes)
data[, bucket := ceiling(rank / bucket_size)]
result <- data[, .(analysis = list(gprofiler2::gost(gene))), by = bucket]
saveRDS(result, file = file_path)
result
}
2022-07-02 23:37:13 +02:00
result[, result := lapply(analysis, function(a) a$result)]
2022-06-22 12:36:14 +02:00
result <- result[, rbindlist(result), by = bucket]
2022-06-22 19:07:15 +02:00
data <- result[, .(count = .N), by = c("bucket", "source")]
2022-07-02 23:37:13 +02:00
data[, total := sum(count), by = bucket]
2022-07-15 08:57:10 +02:00
smooth_model <- loess(total ~ bucket, data, span = 0.3)
bucket_smoothed <- seq(1, nrow(data), 0.1)
total_smoothed <- predict(smooth_model, bucket_smoothed)
2022-06-22 12:36:14 +02:00
2022-07-02 23:37:13 +02:00
fig <- plotly::plot_ly(data) |>
plotly::add_bars(
x = ~bucket,
2022-06-22 12:36:14 +02:00
y = ~count,
2022-06-22 19:07:15 +02:00
color = ~source
) |>
2022-07-02 23:37:13 +02:00
plotly::add_lines(
2022-09-25 20:01:42 +02:00
x = bucket_smoothed,
y = total_smoothed,
2022-07-02 23:37:13 +02:00
name = "All (smoothed)"
) |>
plotly::layout(
2022-07-02 23:37:13 +02:00
xaxis = list(title = glue::glue("Bucket of genes (n = {bucket_size})")),
2022-06-22 12:36:14 +02:00
yaxis = list(title = "Number of associated terms"),
2022-06-22 19:07:15 +02:00
barmode = "stack",
legend = list(title = list(text = "<b>Source of term</b>"))
)
plotly::save_image(fig, image_path, width = 1200, height = 800)
2022-06-22 19:34:39 +02:00
gsea_plot_ranking <- fig
usethis::use_data(gsea_plot_ranking, internal = TRUE, overwrite = TRUE)