KEGG Pathway Analysis in R on Your Own RNA-seq Data
By the end of this guide you will have two tables and a set of images: a ranked table of KEGG pathways enriched among your differentially expressed genes, a second table from a rank-based gene set enrichment run over the same data, and KEGG maps with your fold changes painted onto the boxes. You need R 4.3 or newer, a count matrix from RNA sequencing with gene identifiers you trust, and sample metadata describing what distinguishes the samples. If your data comes from a personal molecular profile, the contrast is usually between your own timepoints rather than between people. That changes the statistics but not the pathway machinery described here.
1. Install the packages and pin what you can
Everything below runs on Bioconductor. Install once, then record versions.
install.packages("BiocManager")
BiocManager::install(c(
"DESeq2", "apeglm", "clusterProfiler", "org.Hs.eg.db",
"enrichplot", "pathview", "KEGGREST", "ggplot2"
))
Two of these packages talk to the network at runtime. clusterProfiler fetches KEGG pathway definitions from the KEGG REST API every time you call enrichKEGG or gseKEGG unless you pass use_internal_data = TRUE, which pulls from a frozen snapshot that is years old. We recommend leaving the default on and caching the download yourself, as in step 7. pathview downloads the KGML file and base PNG for each map it renders.
Record sessionInfo() and the KEGG release string alongside your results. KEGG changes monthly, and a pathway that was significant in March can lose two genes by June.
2. Build a contrast that makes sense for your data
Pathway analysis inherits every weakness of the differential expression step that feeds it. A single RNA-seq sample has no dispersion estimate, so there is no differential expression to speak of. With a longitudinal profile you have two realistic options. The first is a within-person contrast across timepoints with DESeq2, treating the condition of interest as the design variable.
library(DESeq2)
dds <- DESeqDataSetFromMatrix(countData = counts,
colData = meta,
design = ~ batch + state)
keep <- rowSums(counts(dds) >= 10) >= 3
dds <- dds[keep, ]
dds <- DESeq(dds)
res <- lfcShrink(dds, coef = "state_fasted_vs_fed", type = "apeglm")
The keep filter matters more than people expect. Low-count genes inflate the multiple testing burden and drag the Benjamini-Hochberg adjustment down without contributing signal.
The second option, when you have a single sample and a personal baseline, is to rank genes by a z-score against your own prior distribution for each gene. That gives a ranked list suitable for gene set enrichment but not a significance-thresholded list suitable for over-representation. Be explicit with yourself about which you have.
3. Map your identifiers to Entrez gene IDs
KEGG identifies human genes by Entrez ID with an hsa: prefix. If your counts are keyed on Ensembl gene IDs, you have to translate, and you will lose genes doing it.
library(clusterProfiler)
library(org.Hs.eg.db)
res_df <- as.data.frame(res)
res_df$ensembl <- sub("\\..*$", "", rownames(res_df)) # strip version suffix
map <- bitr(res_df$ensembl, fromType = "ENSEMBL",
toType = "ENTREZID", OrgDb = org.Hs.eg.db)
map <- map[!duplicated(map$ENSEMBL), ]
res_df <- merge(res_df, map, by.x = "ensembl", by.y = "ENSEMBL")
Expect bitr to warn that 20 to 40 percent of input IDs failed to map. Most of those are long non-coding RNAs, pseudogenes and novel transcripts that have no Entrez record and therefore no KEGG annotation. That is expected. What is not acceptable is silently dropping the version suffix problem: ENSG00000141510.16 will not match, and sub("\\..*$", "", x) fixes it.
Some Ensembl genes map to several Entrez IDs. Keeping the first, as above, is a defensible default. Keeping all of them double-counts genes in the enrichment test.
4. Over-representation analysis with enrichKEGG
Over-representation analysis asks whether your significant genes fall into a pathway more often than chance, given a background set. The background, called the universe, is the single most abused parameter in this entire field. It must be the set of genes that could have been called significant, which means the genes that survived your expression filter. The set is not every gene in the genome.
sig <- subset(res_df, padj < 0.05 & abs(log2FoldChange) > 0.5)
ora <- enrichKEGG(gene = sig$ENTREZID,
universe = res_df$ENTREZID,
organism = "hsa",
keyType = "kegg",
pAdjustMethod = "BH",
pvalueCutoff = 0.05,
qvalueCutoff = 0.10,
minGSSize = 10,
maxGSSize = 500)
ora <- setReadable(ora, OrgDb = org.Hs.eg.db, keyType = "ENTREZID")
head(as.data.frame(ora), 20)
setReadable swaps Entrez IDs for symbols in the geneID column, which is the difference between a table you can read and a table you cannot. The maxGSSize = 500 cap quietly excludes hsa01100 (Metabolic pathways), a map with well over a thousand genes that is significant in almost every analysis and tells you nothing. Keep the cap.
The output columns worth reading are GeneRatio and BgRatio. A pathway with GeneRatio of 4/180 and BgRatio of 12/11000 is driven by four genes. Treat it as a hypothesis about those four genes. It is not a hypothesis about the pathway.
5. Rank-based enrichment with gseKEGG
Over-representation throws away the ranking and imposes an arbitrary threshold. Gene set enrichment analysis uses the whole ranked list, which is what we prefer when the effect is distributed across many genes of modest effect size. That is the usual situation in a within-person comparison.
ranks <- res_df$log2FoldChange
names(ranks) <- res_df$ENTREZID
ranks <- sort(ranks[!is.na(ranks)], decreasing = TRUE)
set.seed(42)
gsea <- gseKEGG(geneList = ranks,
organism = "hsa",
keyType = "kegg",
minGSSize = 15,
maxGSSize = 500,
pvalueCutoff = 0.05,
pAdjustMethod = "BH",
eps = 0,
nPermSimple = 10000,
seed = TRUE,
verbose = FALSE)
Three arguments here are not decoration. eps = 0 turns off the p-value floor so that strongly enriched sets get a real estimate rather than being clipped at 1e-10. nPermSimple = 10000 raises the permutation count, which fgsea uses to calibrate the multilevel step. seed = TRUE plus set.seed makes the run reproducible, because the permutation step is stochastic and unseeded runs will not match.
Ranking by shrunken log fold change is the choice we default to. Ranking by the Wald statistic or by -log10(pvalue) * sign(log2FoldChange) weights confidence more heavily and will give somewhat different results. Pick one before you look at the output and say which you used.
Ties in the ranking vector degrade GSEA. If many genes share exactly zero fold change, shrinkage has flattened them, and it is worth checking sum(ranks == 0).
6. Plots that carry information
Start with a dot plot split by direction, then move to the maps.
library(enrichplot)
dotplot(gsea, showCategory = 20, split = ".sign") +
ggplot2::facet_grid(. ~ .sign)
gseaplot2(gsea, geneSetID = which(gsea$ID == "hsa04910"),
title = gsea$Description[gsea$ID == "hsa04910"])
For the KEGG map itself, pathview writes a PNG with each gene box coloured by your value. It writes into the current working directory and will overwrite without asking, so set a directory first.
library(pathview)
fc <- res_df$log2FoldChange
names(fc) <- res_df$ENTREZID
dir.create("pathview_out", showWarnings = FALSE)
old <- setwd("pathview_out")
pathview(gene.data = fc,
pathway.id = "hsa04910",
species = "hsa",
gene.idtype = "entrez",
limit = list(gene = 2),
bins = list(gene = 10),
low = list(gene = "#2166AC"),
high = list(gene = "#B2182B"),
out.suffix = "fasted_vs_fed")
setwd(old)
limit = list(gene = 2) caps the colour scale at a log2 fold change of two in either direction. Without it a single extreme gene compresses everything else to grey. You get three files per pathway: the downloaded hsa04910.xml, the base hsa04910.png, and your rendered hsa04910.fasted_vs_fed.png.
Note that KEGG boxes often represent gene families rather than single genes. When several family members map to one box, pathview averages them by default. Set multi.state = FALSE and inspect the returned data frame if that ambiguity matters to your reading.
7. Downloading KEGG data directly
You can and should pull pathway definitions yourself, both for caching and for the metadata that clusterProfiler does not surface. KEGGREST wraps the public REST API.
library(KEGGREST)
keggInfo("hsa") # includes the current release string
paths <- keggList("pathway", "hsa") # named vector of map IDs to titles
links <- keggLink("pathway", "hsa") # gene-to-pathway mapping, long form
entry <- keggGet("hsa04910")[[1]]
str(entry$GENE, list.len = 6)
entry$MODULE
Save links and paths to an RDS file named with the release string. That single step makes an analysis reproducible a year later, when KEGG has moved on. clusterProfiler also exposes download_KEGG("hsa"), which returns the same information in the two-list shape the enrichment functions expect.
The REST API is free for academic use. Commercial use of KEGG data requires a licence from the copyright holder, and that applies to programmatic downloads as much as to the website. Check before you build a product on top of it.
KEGG modules, accessible through enrichMKEGG and gseMKEGG, are worth a run alongside the pathways. A module is a tight functional unit such as a single branch of a biosynthesis route. Modules produce fewer and more interpretable hits than the sprawling maps.
8. When flat gene lists are not enough
Standard over-representation treats a pathway as an unordered bag of genes, which discards the topology that KEGG spent decades curating. Several R packages use that structure instead. pathfindR maps your differentially expressed genes onto a protein interaction network, identifies active subnetworks, and runs enrichment on those subnetworks rather than the raw list. That recovers pathways that a flat test misses.1 It needs a gene symbol, a fold change and a p-value per row, and it is considerably slower than enrichKEGG.
A second alternative is network enrichment, which scores connections between your gene set and a pathway rather than requiring direct overlap. NEArender implements this and is designed for cases where your gene list barely intersects any annotated pathway.2 That case is common with lists dominated by poorly annotated genes.
For a broader pass, running Gene Ontology and disease ontology enrichment next to KEGG gives complementary views of the same list, and the combined workflow is documented as a standard protocol.3
9. Extending beyond RNA to proteins and metabolites
KEGG maps carry both gene products and compounds, which makes them a natural meeting point for transcriptomics, proteomics and metabolomics. Combining measurement layers on shared pathway maps is an established approach for clinical metabolomics and proteomics data.4 In R the practical obstacle is identifier translation, since metabolites arrive as HMDB or KEGG compound IDs and proteins as UniProt accessions.
If you want a graphical route before committing to a scripted pipeline, xOmicsShiny provides cross-omics analysis and pathway mapping inside a Shiny application.5 For integration that builds a network from several data types rather than testing predefined sets, Omics Integrator solves for connected subnetworks linking your hits through known interactions.6 Multi-omics network analysis of this kind has been applied to human tissue to separate distinct stages of aging.7
A caution about interpretation. An enriched pathway is a statement about a gene list relative to a database, and nothing more. It does not establish that the pathway is active, that flux through it has changed, or that anything clinically meaningful is happening in you. Pathway enrichment on personal data generates hypotheses for further measurement. Any question about your health belongs with a clinician who can see the full picture.
Common problems
No gene can be mapped from enrichKEGG almost always means the ID type is wrong. KEGG wants bare Entrez IDs as character vectors, without the hsa: prefix, when keyType = "kegg". Check class(sig$ENTREZID) and head(sig$ENTREZID) before anything else.
Download failures with a 403 or a timeout usually come from a corporate proxy or from curl defaults. Try options(clusterProfiler.download.method = "libcurl") and confirm you can reach https://rest.kegg.jp/info/hsa from the same machine. A one-off retry is often enough, since the API rate-limits bursts.
Empty results from gseKEGG with no error mean nothing passed the adjusted p-value cutoff. Rerun with pvalueCutoff = 1 and inspect the full table before concluding there is no signal. A near-empty result also appears when your ranking vector is unsorted, so verify with is.unsorted(rev(ranks)).
Results that change between runs point at the missing seed. gseKEGG permutes, and set.seed plus seed = TRUE are both required.
Suspiciously long lists of significant pathways usually trace back to the universe. Passing no universe makes clusterProfiler use every annotated gene in the organism, which inflates enrichment for anything expressed in your tissue at all. Pass your filtered gene set.
Heavily overlapping hits, such as several cancer maps appearing together, reflect shared gene membership rather than independent findings. Deduplicate visually with enrichplot::pairwise_termsim followed by emapplot, which clusters terms by gene overlap. Treat each cluster as one result.
Finally, genes with no KEGG annotation are invisible to this entire analysis. Roughly a third of protein-coding genes sit outside every KEGG map. If your top differentially expressed genes are absent from the output, that absence is a property of the database. It says nothing about the biology.
Footnotes
-
Ege Ulgen, Ozan Ozisik, Osman Ugur Sezerman. pathfindR: An R Package for Comprehensive Identification of Enriched Pathways in Omics Data Through Active Subnetworks. Frontiers in Genetics, 2019. https://doi.org/10.3389/fgene.2019.00858 ↩
-
Ashwini Jeggari, Andrey Alexeyenko. NEArender: an R package for functional interpretation of ‘omics’ data via network enrichment analysis. BMC Bioinformatics, 2017. https://doi.org/10.1186/s12859-017-1534-y ↩
-
Vijaykumar Yogesh Muley. Functional Insights Through Gene Ontology, Disease Ontology, and KEGG Pathway Enrichment. Methods in Molecular Biology, 2025. https://doi.org/10.1007/978-1-0716-4546-8_4 ↩
-
Christina Schmidt, Thomas Naake. Multi-Omics Guided Pathway and Network Analysis of Clinical Metabolomics and Proteomics Data. Methods in Molecular Biology, 2026. https://doi.org/10.1007/978-1-0716-5452-1_17 ↩
-
Benbo Gao, Yu H Sun, Xinmin Zhang, et al. xOmicsShiny: an R Shiny application for cross-omics data analysis and pathway mapping. Bioinformatics Advances, 2024. https://doi.org/10.1093/bioadv/vbaf097 ↩
-
Nurcan Tuncbag, Sara J. C. Gosline, Amanda Kedaigle, et al. Network-Based Interpretation of Diverse High-Throughput Datasets through the Omics Integrator Software Package. PLOS Computational Biology, 2016. https://doi.org/10.1371/journal.pcbi.1004879 ↩
-
Nicholas Holzscheck, Jörn Söhle, Boris Kristof, et al. Multi-omics network analysis reveals distinct stages in the human aging progression in epidermal tissue. Aging, 2020. https://doi.org/10.18632/aging.103499 ↩
Pothos builds longitudinal molecular profiles of individuals: whole-genome sequencing, single-cell RNA sequencing, and plasma proteomics, delivered as a detailed report, every data file, and stored cells. Build your profile.