regionalpcs applies principal components analysis separately within each
user-defined genomic region. Each retained component provides a score for each
sample, summarizing a pattern of covariation among that region’s CpGs. Regions
can be promoters, gene bodies, enhancers, or other intervals of interest.
The loadings describe each CpG’s contribution to a regional PC. CpGs with opposite loadings contribute in opposite directions, so a regional PC can capture patterns that are lost when methylation values are averaged.
Install the release compatible with your R and Bioconductor versions:
if (!requireNamespace("BiocManager", quietly = TRUE)) {
install.packages("BiocManager")
}
BiocManager::install("regionalpcs")
The example below uses simulated M-values. An array-data example is included at the end of the vignette.
library(regionalpcs)
library(GenomicRanges)
#> Loading required package: stats4
#> Loading required package: BiocGenerics
#> Loading required package: generics
#>
#> Attaching package: 'generics'
#> The following objects are masked from 'package:base':
#>
#> as.difftime, as.factor, as.ordered, intersect, is.element, setdiff,
#> setequal, union
#>
#> Attaching package: 'BiocGenerics'
#> The following objects are masked from 'package:stats':
#>
#> IQR, mad, sd, var, xtabs
#> The following object is masked from 'package:utils':
#>
#> data
#> The following objects are masked from 'package:base':
#>
#> Filter, Find, Map, Position, Reduce, anyDuplicated, aperm, append,
#> as.data.frame, basename, cbind, colnames, dirname, do.call,
#> duplicated, eval, evalq, get, grep, grepl, is.unsorted, lapply,
#> mapply, match, mget, order, paste, pmax, pmax.int, pmin, pmin.int,
#> rank, rbind, rownames, sapply, saveRDS, scale, sequence, table,
#> tapply, transform, unique, unsplit, which.max, which.min
#> Loading required package: S4Vectors
#>
#> Attaching package: 'S4Vectors'
#> The following object is masked from 'package:utils':
#>
#> findMatches
#> The following objects are masked from 'package:base':
#>
#> I, expand.grid, unname
#> Loading required package: IRanges
#> Loading required package: Seqinfo
The methylation input is a numeric matrix or data frame with CpGs in rows and samples in columns. CpG row names must be unique. At least two samples are required. Values must be finite, and probe filtering should be completed before computing regional PCs. Constant CpGs should be removed; variance fractions are undefined for a region with no variation.
Beta values are proportions on the 0–1 scale. M-values are log2 ratios of methylated to unmethylated signal and are on a different scale. The package does not transform values or standardize each CpG to unit variance. The input scale therefore affects the scores and the number of components retained.
We simulate three regions with six CpGs each. CpGs within a region share a sample-level pattern, with independent noise added to each measurement.
set.seed(2026)
n_samples <- 40L
n_regions <- 3L
cpgs_per_region <- 6L
n_cpgs <- n_regions * cpgs_per_region
region_index <- rep(seq_len(n_regions), each = cpgs_per_region)
latent <- matrix(rnorm(n_regions * n_samples), nrow = n_regions)
mvals <- 2 * latent[region_index, ] +
matrix(rnorm(n_cpgs * n_samples, sd = 0.3), nrow = n_cpgs)
rownames(mvals) <- paste0("cg", seq_len(n_cpgs))
colnames(mvals) <- paste0("sample", seq_len(n_samples))
cpg_gr <- GRanges(
seqnames = "chr1",
ranges = IRanges(start = rep(c(1000, 2000, 3000), each = cpgs_per_region) +
rep(seq_len(cpgs_per_region), n_regions), width = 1)
)
names(cpg_gr) <- rownames(mvals)
regions_gr <- GRanges(
seqnames = "chr1",
ranges = IRanges(start = c(1000, 2000, 3000), width = 100)
)
names(regions_gr) <- c("region-A", "region-B", "region-C")
For real genomic inputs, both GRanges objects must use the same genome build
and compatible chromosome names. create_region_map() does not lift coordinates
between builds. Name the CpG ranges with the same IDs used in the methylation
matrix, and name the region ranges with your intended region IDs.
region_map <- create_region_map(cpg_gr, regions_gr)
head(region_map)
#> gene_id cpg_id
#> 1 region-A cg1
#> 2 region-A cg2
#> 3 region-A cg3
#> 4 region-A cg4
#> 5 region-A cg5
#> 6 region-A cg6
The first two columns of a region map contain region IDs and CpG IDs, respectively. Column names are ignored. A map can also be supplied directly:
custom_map <- data.frame(
region_id = names(regions_gr)[region_index],
cpg_id = rownames(mvals)
)
A CpG can contribute to multiple overlapping regions. Repeated copies of the same region–CpG pair are also preserved and give that CpG repeated influence; remove accidental duplicate pairs before analysis. Regions are returned in first-occurrence order, and CpGs retain their order within each region.
All CpGs in the map must occur in the methylation input. If the map was created before probe filtering, explicitly restrict it to the measured probes:
region_map <- region_map[region_map$cpg_id %in% rownames(mvals), , drop = FALSE]
stopifnot(nrow(region_map) > 0L)
res <- compute_regional_pcs(mvals, region_map, pc_method = "gd")
#> Using Gavish-Donoho method
names(res)
#> [1] "regional_pcs" "percent_variance" "loadings" "info"
res$info
#> region est_dim num_cpgs
#> [1,] "region-A" 1 6
#> [2,] "region-B" 1 6
#> [3,] "region-C" 1 6
The output contains:
| Element | Interpretation |
|---|---|
regional_pcs |
Retained PCs in rows, samples in columns. |
percent_variance |
Within-region variance fractions, one row per PC. |
loadings |
Named list of CpG-by-PC data frames, one per region. |
info |
Metadata matrix: region, est_dim, and num_cpgs. |
percent_variance contains fractions of total within-region variance; multiply
by 100 for percentages. The info matrix combines region IDs and counts. The
example below converts its columns to a data frame with explicit column types.
res$regional_pcs[, seq_len(4), drop = FALSE]
#> sample1 sample2 sample3 sample4
#> region-A-PC1 -3.735772 -0.469399 2.940481 1.576529
#> region-B-PC1 -4.826073 -3.220523 -5.049884 -1.636544
#> region-C-PC1 -1.372090 11.213898 -1.030050 2.657545
100 * res$percent_variance
#> percent_variance_explained
#> region-A-PC1 97.64306
#> region-B-PC1 98.35018
#> region-C-PC1 98.59647
res$loadings[["region-A"]]
#> PC1
#> cg1 -0.3982037
#> cg2 -0.4165488
#> cg3 -0.3916666
#> cg4 -0.4318998
#> cg5 -0.4113715
#> cg6 -0.3984398
info <- data.frame(
region = as.character(unlist(res$info[, "region"])),
est_dim = as.integer(unlist(res$info[, "est_dim"])),
num_cpgs = as.integer(unlist(res$info[, "num_cpgs"]))
)
info
#> region est_dim num_cpgs
#> 1 region-A 1 6
#> 2 region-B 1 6
#> 3 region-C 1 6
Score row names have the form region-ID-PC1. Region IDs can themselves contain
hyphens, so split at the final -PC<number> suffix if you need separate fields:
score_ids <- rownames(res$regional_pcs)
score_key <- data.frame(
region = sub("-PC[0-9]+$", "", score_ids),
pc = sub("^.*-(PC[0-9]+)$", "\\1", score_ids)
)
score_key
#> region pc
#> 1 region-A PC1
#> 2 region-B PC1
#> 3 region-C PC1
PCA signs are arbitrary: simultaneously reversing a component’s scores and loadings represents the same component. A positive PC score does not by itself mean higher average methylation. Interpret scores together with the loadings.
compute_regional_pcs() defaults to Gavish–Donoho ("gd"). Use "mp" for
Marchenko–Pastur:
mp_res <- compute_regional_pcs(mvals, region_map, pc_method = "mp")
#> Using Marchenko-Pastur method
mp_res$info
#> region est_dim num_cpgs
#> [1,] "region-A" 1 6
#> [2,] "region-B" 1 6
#> [3,] "region-C" 1 6
Both methods use eigenvalues (sdev^2) from PCAtools::pca(). CpGs are
centered across samples but are not scaled to unit variance. The noise variance
passed
to both selection methods is fixed at 1. Regional noise is not estimated, and
the threshold does not automatically adjust to a change in input scale.
Beta values and M-values can therefore yield different retained dimensions.
The PCAtools selection routines retain at least one component, including when no eigenvalue exceeds the threshold. Retention is therefore not a significance test. The number of CpGs and samples also limits the regional dimension; a single-CpG region has only one component.
The following example uses M-values from minfiData and hg19 promoter regions.
It requires additional annotation packages and is not evaluated when this
vignette is built.
BiocManager::install(c("minfi", "minfiData", "GenomicFeatures",
"TxDb.Hsapiens.UCSC.hg19.knownGene"))
data("MsetEx.sub", package = "minfiData")
array_mvals <- minfi::getM(MsetEx.sub)
gset <- minfi::mapToGenome(MsetEx.sub)
array_cpgs <- GenomicRanges::granges(gset)
txdb <- TxDb.Hsapiens.UCSC.hg19.knownGene::TxDb.Hsapiens.UCSC.hg19.knownGene
promoters_gr <- GenomicRanges::promoters(GenomicFeatures::genes(txdb),
upstream = 1000, downstream = 0)
array_map <- create_region_map(array_cpgs, promoters_gr)
array_map <- array_map[
array_map$cpg_id %in% rownames(array_mvals), , drop = FALSE]
array_res <- compute_regional_pcs(array_mvals, array_map, pc_method = "gd")
Transpose res$regional_pcs when a downstream model expects samples in rows.
Match phenotype and covariate data to sample IDs explicitly before fitting any
model. Adjust for relevant technical and biological covariates, and account for
multiple testing across the regional components being tested. Regional PCA does
not itself remove confounding or perform differential methylation testing.
sample_scores <- t(res$regional_pcs)
stopifnot(identical(rownames(sample_scores), colnames(mvals)))
dim(sample_scores)
#> [1] 40 3
For prediction, PCA should be fitted within the training data. Held-out samples must use the training centering values and loadings. The package does not currently provide a separate projection function for new samples.
sessionInfo()
#> R version 4.6.1 (2026-06-24)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 24.04.5 LTS
#>
#> Matrix products: default
#> BLAS: /home/biocbuild/bbs-3.24-bioc/R/lib/libRblas.so
#> LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.12.0 LAPACK version 3.12.0
#>
#> locale:
#> [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
#> [3] LC_TIME=en_GB LC_COLLATE=C
#> [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] GenomicRanges_1.66.0 Seqinfo_1.4.0 IRanges_2.48.0
#> [4] S4Vectors_0.52.0 BiocGenerics_0.60.0 generics_0.1.4
#> [7] regionalpcs_1.12.0 BiocStyle_2.42.0
#>
#> loaded via a namespace (and not attached):
#> [1] gtable_0.3.6 xfun_0.62
#> [3] bslib_0.12.0 ggplot2_4.0.4
#> [5] PCAtools_2.26.0 ggrepel_0.9.8
#> [7] lattice_0.23-1 vctrs_0.7.3
#> [9] tools_4.6.1 parallel_4.6.1
#> [11] tibble_3.3.1 pkgconfig_2.0.3
#> [13] Matrix_1.7-6 RColorBrewer_1.1-3
#> [15] S7_1.0.0 sparseMatrixStats_1.26.0
#> [17] dqrng_0.4.1 lifecycle_1.0.5
#> [19] compiler_4.6.1 farver_2.1.2
#> [21] stringr_1.6.0 codetools_0.2-20
#> [23] htmltools_0.5.9 sass_0.5.0
#> [25] yaml_2.3.12 pillar_1.11.1
#> [27] jquerylib_0.1.4 BiocParallel_1.48.0
#> [29] cachem_1.1.0 DelayedArray_0.40.0
#> [31] abind_1.4-8 tidyselect_1.2.1
#> [33] rsvd_2.0.0 digest_0.6.39
#> [35] stringi_1.8.9 BiocSingular_1.30.0
#> [37] dplyr_1.2.1 reshape2_1.4.5
#> [39] bookdown_0.48 cowplot_1.2.0
#> [41] fastmap_1.2.0 grid_4.6.1
#> [43] cli_3.6.6 SparseArray_1.14.0
#> [45] magrittr_2.0.5 S4Arrays_1.14.0
#> [47] dichromat_2.0-1 DelayedMatrixStats_1.36.0
#> [49] scales_1.4.0 rmarkdown_2.32
#> [51] XVector_0.54.0 matrixStats_1.5.0
#> [53] otel_0.3.0 ScaledMatrix_1.22.0
#> [55] beachmat_2.30.0 evaluate_1.0.5
#> [57] knitr_1.52 irlba_2.4.1
#> [59] rlang_1.3.0 Rcpp_1.1.2
#> [61] RMTstat_0.3.2 glue_1.8.1
#> [63] BiocManager_1.30.27 jsonlite_2.0.0
#> [65] plyr_1.8.9 R6_2.6.1
#> [67] MatrixGenerics_1.26.0