This function performs Gene Set Enrichment Analysis (GSEA) on PICRUSt2 predicted functional data to identify enriched pathways between different conditions.
Usage
pathway_gsea(
abundance,
metadata,
group,
pathway_type = "KEGG",
method = "fry",
covariates = NULL,
contrast = NULL,
inter.gene.cor = NA_real_,
rank_method = "signal2noise",
nperm = 1000,
min_size = 5,
max_size = 500,
p_adjust_method = "BH",
seed = 42,
go_category = "all",
organism = "ko",
p.adjust = NULL,
comparison = NULL,
transformation = c("logCPM", "voom"),
gene_sets = NULL,
filter_for_prokaryotes = TRUE,
sequencing_depth = NULL
)Arguments
- abundance
A data frame containing gene/enzyme abundance data, with feature IDs in row names and samples as columns. Data frames may also provide a leading non-numeric feature ID column (for example
#NAME,feature, orpathway); it is converted to row names automatically. Values must be finite, non-missing, and non-negative count-like abundances; negative or non-finite values are rejected rather than being coerced to zero. For KEGG analysis: features should be KO IDs (e.g., K00001). For MetaCyc analysis: features should be EC numbers (e.g., EC:1.1.1.1 or 1.1.1.1), NOT pathway IDs. MetaCyc pathway-like identifiers are rejected because GSEA requires gene/enzyme-level input; usepathway_daafor pathway-level MetaCyc abundance tables. For GO analysis: features should be KO IDs that will be mapped to GO terms. NOTE: This function requires gene-level data, not pathway-level abundances. For pathway abundance analysis, usepathway_daainstead- metadata
A data frame containing sample metadata. After sample alignment, all retained samples must have non-missing, non-empty values in the grouping column.
- group
A character string specifying the column name in metadata that contains the grouping variable
- pathway_type
A single character string specifying the pathway type: "KEGG", "MetaCyc", or "GO"
- method
A single character string specifying the GSEA method:
"fry"(default): Self-contained rotation gene set test using limma's fry function. Tests whether the KOs in a set change in a consistent direction between groups."camera": Competitive gene set test using limma's camera function. Tests whether a set changes more than the other KOs, with an inter-gene correlation adjustment."fgsea": Fast preranked GSEA implementation. Note: preranked methods may produce unreliable p-values due to not accounting for inter-gene correlations (Wu et al., 2012)."GSEA"or"clusterProfiler": clusterProfiler's GSEA implementation.
- covariates
A character vector specifying column names in metadata to use as covariates for adjustment. Only supported when method is "camera" or "fry"; supplying covariates with preranked methods is an error because those methods use a precomputed rank vector rather than a design matrix. Default is NULL (no covariates). Covariate values must be complete for all aligned samples; rows with missing model variables are rejected rather than being silently dropped by
model.matrix(). The resulting design matrix must also be finite and full rank; constant or fully confounded covariates are rejected. Example:covariates = c("age", "sex", "BMI")- contrast
For "camera" or "fry" methods, specify the coefficient or contrast to test. Supplying
contrastwith preranked methods is an error; usecomparisoninstead. DefaultNULLautomatically tests the single non-reference group coefficient in two-group designs. Multi-group designs must specify this explicitly. A character value must exactly match a design column name or a non-reference group level; substring matching is not used. A numeric scalar is treated as a design-column index, and a numeric vector must have length equal to the number of design columns. Named numeric vectors are matched and reordered by design column names; unnamed numeric vectors are interpreted in design column order.- inter.gene.cor
Numeric value specifying the inter-gene correlation for the camera method. The default
NAestimates the correlation from the data separately for each gene set. Predicted functional profiles are linear combinations of reference-genome content, so features in the same set are often strongly correlated; a small fixed value such as 0.01 (the default before version 2.6.0) can then underestimate the variance and produce anti-conservative p-values. Supply a fixed value only when it is justified for the data.- rank_method
A single character string specifying the ranking statistic for preranked methods (fgsea, GSEA, clusterProfiler): "signal2noise", "t_test", "log2_ratio", or "diff_abundance"
- nperm
An integer specifying the number of permutations (for clusterProfiler method only). The fgsea method uses adaptive multilevel splitting and does not require a fixed permutation count.
- min_size
An integer specifying the minimum gene set size
- max_size
An integer specifying the maximum gene set size
- p_adjust_method
A character string specifying the p-value adjustment method
- seed
An integer specifying the random seed for reproducibility
- go_category
A single character string specifying GO category to use. "all" (default) uses all categories present in the reference data. Valid categories are determined by the reference data (currently MF and CC). See
table(ko_to_go_reference$category)for available categories.- organism
Deprecated and has no effect. The KEGG and GO reference data bundled with ggpicrust2 are KO-based (organism-independent), so gene sets are returned in KO space regardless of this argument. Retained only for signature compatibility; passing any value other than the default
"ko"emits a deprecation warning. Will be removed in a future release.- p.adjust
Deprecated alias for
p_adjust_method. Do not supply both parameters with different values.- comparison
For preranked methods only (
"fgsea","GSEA", or"clusterProfiler"), an optional length-2 character vectorc(group1, group2)defining the ranking direction. Ranking statistics are calculated as group1 versus group2: positivesignal2noise,t_test,diff_abundance, andlog2_ratiovalues indicate higher abundance ingroup1(forlog2_ratio,log2(group1 / group2)). IfNULL, exactly two aligned group levels must be present and their factor-level order is used. Multi-group preranked analyses must specifycomparisonexplicitly.- transformation
Transformation for camera/fry.
"logCPM"(the default) useslog2(1e6 * abundance / column_total + 0.5)with abundance-trend variance moderation and no voom weights. It is invariant to positive per-sample rescaling, which suits predicted or relative abundances whose units are not observed read counts. Requires positive sample totals."voom"(the default before version 2.6.0) uses count-dependent observation weights and is appropriate only for genuine read counts; its results change when the same table is multiplied by a constant. This parameter applies only to camera/fry; supplying it with a preranked method is an error. Neither transformation accounts for uncertainty from the upstream functional prediction. Results also depend on the measured feature universe and, for camera, the correlation model.- gene_sets
Optional named list of feature identifiers for explicitly defined gene sets. When supplied, replaces the bundled sets for all methods; size filtering and multiple-testing adjustment still apply. Identifiers must match the normalized abundance row names.
pathway_typestill controls input identifier handling. Do not combine custom sets withorganism,go_categoryorfilter_for_prokaryotes; these are bundled-reference selection arguments.- filter_for_prokaryotes
Logical. For KEGG gene sets, TRUE (default) keeps maps that KEGG draws for prokaryotic genomes and removes Organismal Systems and Human Diseases maps, except bacterial infection and antimicrobial resistance, so that the tested pathways match those kept by
ko2kegg_abundance. Ignored whengene_setsis supplied and for MetaCyc and GO.- sequencing_depth
Optional read depth of the data the profile was derived from, for camera and fry only. Either the name of a metadata column or a numeric vector named by sample ID. For PICRUSt2 output, use the column sums of the ASV (or OTU) count table given to PICRUSt2, not the column sums of the predicted table, which depend on community composition. The centered natural log of the depth is added to the design as the covariate
log_sequencing_depth. Supply it when depth differs between groups and some samples are shallowly sequenced: with logCPM, zeros and low counts then fall unevenly between groups, and fry can report false pathways under the null. DefaultNULL(no depth adjustment).
Value
A data frame containing GSEA results with columns:
pathway_id: Pathway identifierpathway_name: Pathway name/descriptionsize: Number of genes in the pathwaydirection: Direction of enrichment ("Up" or "Down", for camera/fry)pvalue: Raw p-valuep.adjust: Adjusted p-value (FDR)method: The method used for analysis
For fgsea/clusterProfiler methods, additional columns include ES, NES,
leading_edge, group1, and group2. Positive ES/NES values are in the
group1 versus group2 direction. For camera/fry methods,
limma does not return NES; ggpicrust2 retains a legacy NES column
containing a signed -log10(pvalue) score for visualization
compatibility and labels it with score_type and
score_label.
Details
Method Selection:
The fry method (default):
Performs a self-contained test: do the KOs in the set change in a consistent direction between groups?
Uses sample rotations, so the correlation among KOs in a set is accounted for without a fixed correlation assumption
Supports covariate adjustment through the design matrix
The camera method:
Performs a competitive test: does the set change more than the other KOs?
Adjusts for inter-gene correlation estimated separately for each set (default)
Supports covariate adjustment through the design matrix
In a predicted metagenome, a shift in a dominant taxon moves many KOs together, so a competitive test has little power to single out a set even when its members change. Use camera when the question is relative enrichment; use fry (the default since version 2.6.0) when the question is whether a set changes.
Preranked methods use a ranked-feature null rather than camera's competitive
model with a correlation adjustment. The hypotheses and input assumptions
differ; neither method is universally calibrated for predicted abundances.
For these methods, positive ES/NES values indicate gene-set enrichment near
the top of the ranked list. With comparison = c(group1, group2), the
top of the list corresponds to features higher in group1; reverse
comparison to reverse the biological direction.
Covariate Adjustment:
When using method = "camera" or method = "fry", you can adjust for
confounding variables by specifying them in the covariates parameter.
This is particularly important in microbiome studies where factors like age, sex,
BMI, and batch effects can influence results.
References
Wu, D., & Smyth, G. K. (2012). Camera: a competitive gene set test accounting for inter-gene correlation. Nucleic Acids Research, 40(17), e133.
Wu, D., Lim, E., Vaillant, F., Asselin-Labat, M. L., Visvader, J. E., & Smyth, G. K. (2010). ROAST: rotation gene set tests for complex microarray experiments. Bioinformatics, 26(17), 2176-2182.
Examples
if (FALSE) { # \dontrun{
# Load example data
data(ko_abundance)
data(metadata)
# Prepare abundance data
abundance_data <- as.data.frame(ko_abundance)
rownames(abundance_data) <- abundance_data[, "#NAME"]
abundance_data <- abundance_data[, -1]
# Method 1: fry (default), a self-contained test of each set
gsea_results <- pathway_gsea(
abundance = abundance_data,
metadata = metadata,
group = "Environment",
pathway_type = "KEGG",
method = "fry"
)
# Method 2: fry with covariate adjustment
gsea_results_adj <- pathway_gsea(
abundance = abundance_data,
metadata = metadata,
group = "Environment",
covariates = "Mouse_Sex",
pathway_type = "KEGG",
method = "fry"
)
# fry adjusted for 16S read depth, e.g. from the DADA2 sequence table
# given to PICRUSt2: depth <- colSums(asv_counts)
# gsea_results_depth <- pathway_gsea(
# abundance = abundance_data,
# metadata = metadata,
# group = "Environment",
# sequencing_depth = depth
# )
# Method 3: camera, a competitive test of relative enrichment
gsea_results_camera <- pathway_gsea(
abundance = abundance_data,
metadata = metadata,
group = "Environment",
pathway_type = "KEGG",
method = "camera"
)
# Method 4: A different null, using a prespecified preranked comparison
gsea_results_fgsea <- pathway_gsea(
abundance = abundance_data,
metadata = metadata,
group = "Environment",
pathway_type = "KEGG",
method = "fgsea",
comparison = c("Pro-survival", "Pro-inflammatory"),
seed = 42
)
# Visualize results
visualize_gsea(gsea_results, plot_type = "enrichment_plot", n_pathways = 10)
} # }