This vignette starts from a precomputed
methylTFRdeviations object and shows a downstream analysis
of methylTFR
deviation scores: PCA, differential testing between two groups, a
comparison of two contrasts, and the motif footprints behind the
scores.
The biological setting is the naive-to-memory transition in human T
cells, in the cytotoxic (CD8, Tc) and helper (CD4,
Th) compartments. All quantities are derived from DNA
methylation.
The following methylTFR functionality is demonstrated:
| Step | Function |
|---|---|
| Access bias-corrected deviation scores | deviations() |
| Access row-wise deviation Z-scores | deviationZScores() |
| Rank motifs by activity variability | computeZScoreVariability() |
| Test motifs between two groups | differentialDeviationTest() |
| Plot observed and expected methylation | plotExpectedFootprint() |
| Plot the bias-corrected footprint | plotMotifFootprint() |
Deviation scores themselves are computed with
runMethylTFR() from per-sample methylation files, or with
runMethylTFRFromRnBeads() directly from a preprocessed
RnBeads object. Both are covered in the Get started vignette; this one begins from
their output.
library(methylTFR)
library(SummarizedExperiment)
library(ggplot2)
library(ComplexHeatmap)
library(circlize)A single palette is used for the seven cell types throughout, so that a colour denotes the same cell type in every figure.
immuneDeviations contains simulated deviation scores for
seven human immune cell types, with one column per simulated sample and
one row per JASPAR2020 motif. Four of the seven are T cell subsets,
naive and memory in the cytotoxic and helper compartments; the remaining
three provide a lineage contrast.
The simulation is based on methylTFR scores of
pseudobulk methylomes from the immune cell atlas of Gündüz et
al. (2025, doi:10.1101/2025.09.09.675101).
Those data are under controlled access, so only the mean and standard
deviation of each motif in each cell type were taken from them, and 10
samples per cell type were drawn from a normal distribution with these
parameters. Differences between cell types are therefore kept, while
correlations between motifs within a cell type are not. Sources and
terms of all bundled data are listed in ?methylTFR.
load(system.file("extdata", "immuneDeviations.rda", package = "methylTFR"))
immuneDeviations
#> class: methylTFRdeviations
#> dim: 629 70
#> metadata(6): motifSet genome ... citation contrastOrientation
#> assays(2): deviations z
#> rownames(629): FOXF2 FOXD1 ... ZNF263 CREM
#> rowData names(1): motifs
#> colnames(70): Tc-Naive_01 Tc-Naive_02 ... Monocyte_09 Monocyte_10
#> colData names(1): cell_type
table(colData(immuneDeviations)$cell_type)
#>
#> Tc-Naive Tc-Mem Th-Naive Th-Mem B-cell NK-cell Monocyte
#> 10 10 10 10 10 10 10Provenance is stored in the object metadata.
metadata(immuneDeviations)
#> $motifSet
#> [1] "jaspar2020_distal"
#>
#> $genome
#> [1] "hg38"
#>
#> $source
#> [1] "Simulated from per-cell-type motif means and SDs of pseudobulk single-cell methylomes of human immune cells; see inst/scripts/tcell_data.R"
#>
#> $simulated
#> [1] TRUE
#>
#> $citation
#> [1] "Gunduz IB, Wei B, Chen DC, Wang W, Hariharan M, Norell T, et al. Dissecting epigenome dynamics in human immune cells upon viral and chemical exposure by multimodal single-cell profiling. bioRxiv 2025.09.09.675101. doi:10.1101/2025.09.09.675101"
#>
#> $contrastOrientation
#> [1] "naive minus memory"The object is made by inst/scripts/tcell_data.R.
A methylTFRdeviations object stores two matrices.
deviations() returns the bias-corrected deviation scores.
deviationZScores() returns the same values standardised
row-wise across samples.
dev_mat <- deviations(immuneDeviations)
z_mat <- deviationZScores(immuneDeviations)
round(dev_mat[seq_len(3), seq_len(4)], 4)
#> Tc-Naive_01 Tc-Naive_02 Tc-Naive_03 Tc-Naive_04
#> FOXF2 -0.0118 -0.0297 -0.0295 -0.0175
#> FOXD1 -0.0435 -0.0308 -0.0308 -0.0324
#> IRF2 -0.0614 -0.0581 -0.0368 -0.0665The two assays serve different purposes. Deviation scores are the quantitative estimate of motif activity and are the correct input to statistical tests. Row-wise Z-scores rescale every motif to a common spread, which makes rows comparable in a heatmap, but by construction the standard deviation of each row is 1 (up to rounding).
Deviation scores form a low-dimensional feature set, so principal component analysis can be applied to the matrix directly.
pca <- prcomp(t(dev_mat), center = TRUE, scale. = FALSE)
var_expl <- round(100 * pca$sdev^2 / sum(pca$sdev^2), 1)
pca_df <- data.frame(
PC1 = pca$x[, 1], PC2 = pca$x[, 2],
cell_type = colData(immuneDeviations)$cell_type
)
ggplot(pca_df, aes(PC1, PC2, colour = cell_type)) +
geom_point(size = 2, alpha = 0.85) +
scale_colour_manual(values = cell_type_colors, name = NULL) +
labs(
x = sprintf("PC1 (%.1f%%)", var_expl[1]),
y = sprintf("PC2 (%.1f%%)", var_expl[2])
) +
theme_classic()PC1 separates the myeloid samples from the lymphoid ones. PC2 resolves the T cell subsets by differentiation state: the two naive subsets group together, as do the two memory subsets, while the CD8 and CD4 compartments overlap. Differentiation state therefore accounts for more of the variation in motif activity than the CD8/CD4 distinction does.
Before testing a specific contrast,
computeZScoreVariability() ranks motifs by how much their
activity varies across the dataset, without requiring group labels. Each
sample is calibrated against a null estimated across motifs, so a
variability above 1 indicates a motif varying more than the background
spread of that sample. P-values come from a chi-squared test against
that null.
variability <- computeZScoreVariability(immuneDeviations, method = "robust")
variability <- variability[order(-variability$variability), ]
head(variability, 8)
#> motifs variability p_value p_value_adjusted
#> 252 CEBPE 2.459416 2.794882e-51 1.757981e-48
#> 251 CEBPB 2.417111 1.084970e-48 3.412232e-46
#> 253 CEBPG 2.248517 5.379480e-39 1.127898e-36
#> 554 CEBPD 2.094378 5.128992e-31 8.065340e-29
#> 269 GMEB2 2.035563 3.371313e-28 4.241112e-26
#> 553 CEBPA 2.029171 6.704530e-28 7.028582e-26
#> 69 DBP 1.963685 6.288681e-25 5.650829e-23
#> 527 CEBPG(var.2) 1.705016 9.038538e-15 7.106551e-13The highest-ranking motifs belong to the CEBP family, which distinguish the myeloid lineage from the lymphoid ones. Unlike the test below, this screen needs no group labels.
This function reads the deviations assay. Supplying
row-wise Z-scores instead would be uninformative, because their per-row
standard deviation is 1 for every motif, as shown above.
Optional bootstrap confidence bounds are available via
bootstrap = TRUE.
differentialDeviationTest() tests each motif for a
difference in deviation scores between two groups. With two groups and
parametric = TRUE the test is a Welch t-test; p-values are
adjusted with the Benjamini-Hochberg procedure.
With two groups, the returned mean_difference column is
the mean of the first factor level minus the mean of the second. The
levels below are naive then memory, so a positive value indicates a
higher deviation score in the naive state. The helper also adds the same
contrast on the Z-score scale.
compare_subsets <- function(object, naive, memory) {
grp_all <- colData(object)$cell_type
keep <- grp_all %in% c(naive, memory)
grp <- factor(as.character(grp_all[keep]), levels = c(naive, memory))
dev_sub <- deviations(object)[, keep, drop = FALSE]
z_sub <- deviationZScores(object)[, keep, drop = FALSE]
is_naive <- grp == naive
res <- differentialDeviationTest(
deviations = dev_sub,
groups = grp,
alternative = "two.sided",
parametric = TRUE,
padjMethod = "BH"
)
res$diff <- res$mean_difference
res$zdiff <- rowMeans(z_sub[, is_naive, drop = FALSE]) -
rowMeans(z_sub[, !is_naive, drop = FALSE])
res[order(res$p_value_adjusted), ]
}
tc_res <- compare_subsets(immuneDeviations, "Tc-Naive", "Tc-Mem")
th_res <- compare_subsets(immuneDeviations, "Th-Naive", "Th-Mem")
head(tc_res, 8)
#> motifs p_value p_value_adjusted mean_difference diff
#> BATF3 BATF3 5.907472e-13 3.715800e-10 0.12517 0.12517
#> TBX2 TBX2 1.221095e-12 3.840344e-10 0.08789 0.08789
#> FOSL2::JUN FOSL2::JUN 2.668263e-12 5.594458e-10 0.10852 0.10852
#> FOS::JUNB FOS::JUNB 5.858102e-12 9.211866e-10 0.10839 0.10839
#> EOMES EOMES 8.468338e-12 1.065317e-09 0.07232 0.07232
#> FOSL1::JUNB FOSL1::JUNB 2.226076e-11 2.333670e-09 0.11128 0.11128
#> JUN(var.2) JUN(var.2) 5.365713e-11 4.821477e-09 0.12011 0.12011
#> BATF::JUN BATF::JUN 9.836405e-11 6.874554e-09 0.11483 0.11483
#> zdiff
#> BATF3 2.2076
#> TBX2 1.9263
#> FOSL2::JUN 1.8402
#> FOS::JUNB 1.8041
#> EOMES 1.9925
#> FOSL1::JUNB 1.8089
#> JUN(var.2) 2.1445
#> BATF::JUN 1.9947The helper above returns two effect sizes on different scales.
diff is the difference in raw deviation scores;
zdiff is the same contrast expressed in Z-score units. A
threshold must be applied on the scale it was defined for, since the two
ranges differ by an order of magnitude.
The motifs with the strongest change in the CD8 comparison are shown as row-wise Z-scores across all seven cell types, drawn with ComplexHeatmap. Columns are split by cell type and annotated with the palette defined above; rows are clustered, so motifs with a similar activity profile are placed together.
top_motifs <- head(
tc_res$motifs[
tc_res$p_value_adjusted < 0.05 & abs(tc_res$zdiff) > 0.5
], 25
)
sample_order <- order(colData(immuneDeviations)$cell_type)
z_top <- as.matrix(z_mat[top_motifs, sample_order, drop = FALSE])
subset_of <- colData(immuneDeviations)$cell_type[sample_order]
z_lim <- max(abs(z_top))
z_col <- colorRamp2(
c(-z_lim, 0, z_lim),
c("#2166AC", "white", "#B2182B")
)
column_ann <- HeatmapAnnotation(
`cell type` = subset_of,
col = list(`cell type` = cell_type_colors),
annotation_name_gp = grid::gpar(fontsize = 8),
annotation_legend_param = list(`cell type` = list(
title = "",
labels_gp = grid::gpar(fontsize = 8)
))
)
heat <- Heatmap(
z_top,
name = "Z-score",
col = z_col,
top_annotation = column_ann,
column_split = subset_of,
cluster_columns = FALSE,
cluster_rows = TRUE,
show_row_dend = TRUE,
show_column_names = FALSE,
row_names_gp = grid::gpar(fontsize = 7),
column_title_gp = grid::gpar(fontsize = 7),
row_dend_width = grid::unit(8, "mm"),
heatmap_legend_param = list(
title_gp = grid::gpar(fontsize = 8, fontface = "bold"),
labels_gp = grid::gpar(fontsize = 8),
legend_height = grid::unit(25, "mm")
)
)
draw(heat, merge_legend = TRUE)Most of the selected motifs belong to the AP-1 family. Their pattern
is consistent across both T compartments, high in the naive subsets and
low in the memory subsets, and lowest of all in monocytes. The T-box
motifs EOMES, TBR1 and TBX2
follow a different pattern, low in cytotoxic memory T cells and in NK
cells, which is where those factors are active. Including the non-T
lineages makes clear that the memory signature is not simply a general
lymphoid-myeloid contrast.
The CD8 and CD4 contrasts are computed from disjoint sets of samples. Plotting the Z-score differences against each other shows whether the two compartments identify the same motifs. Each motif is classified by where it reaches significance: in both compartments, in CD4 only, in CD8 only, or in neither.
z_cut <- 0.5
shared <- intersect(tc_res$motifs, th_res$motifs)
tc_i <- match(shared, tc_res$motifs)
th_i <- match(shared, th_res$motifs)
agree <- data.frame(
motifs = shared,
tc = tc_res$zdiff[tc_i],
th = th_res$zdiff[th_i]
)
sig_tc <- tc_res$p_value_adjusted[tc_i] < 0.05 & abs(agree$tc) > z_cut
sig_th <- th_res$p_value_adjusted[th_i] < 0.05 & abs(agree$th) > z_cut
agree$category <- factor(
ifelse(
sig_tc & sig_th, "both",
ifelse(sig_th, "CD4 only", ifelse(sig_tc, "CD8 only", "neither"))
),
levels = c("both", "CD4 only", "CD8 only", "neither")
)
rho <- cor(agree$tc, agree$th)
round(rho, 3)
#> [1] 0.787
table(agree$category)
#>
#> both CD4 only CD8 only neither
#> 157 63 117 292category_colors <- c(
"both" = "#D7191C",
"CD4 only" = "#1A9641",
"CD8 only" = "#2C7BB6",
"neither" = "grey75"
)
ranked <- agree[order(agree$tc + agree$th), ]
labelled <- rbind(head(ranked, 4), tail(ranked, 4))
agree_ord <- agree[order(agree$category, decreasing = TRUE), ]
ggplot(agree_ord, aes(tc, th)) +
geom_hline(yintercept = 0, linetype = "dashed", colour = "grey60") +
geom_vline(xintercept = 0, linetype = "dashed", colour = "grey60") +
geom_point(aes(colour = category), size = 1.8, alpha = 0.85) +
geom_text(
data = labelled, aes(label = motifs),
size = 3, vjust = -0.8, check_overlap = TRUE
) +
scale_colour_manual(
values = category_colors,
breaks = names(category_colors),
name = "differential in"
) +
labs(
x = "CD8: Z-score difference (naive - memory)",
y = "CD4: Z-score difference (naive - memory)",
title = sprintf("Pearson r = %.2f", rho)
) +
theme_classic() +
theme(
legend.position = "bottom",
axis.title.x = element_text(colour = category_colors[["CD8 only"]]),
axis.title.y = element_text(colour = category_colors[["CD4 only"]])
)The effect sizes are correlated and share sign for most motifs, so the same factors are recovered in both compartments. Motifs differential in both compartments (red) lie along the diagonal, away from the origin. The compartment-specific motifs (green and blue) sit closer to the axis they are specific to, and most of them fall just short of the threshold in the other compartment rather than changing in the opposite direction.
A deviation score summarises a footprint: methylation at the motif centre relative to its flanking regions, corrected for GC content. Plotting the footprint shows the profile the score is derived from.
The footprint functions require base-resolution methylation calls and
the motif annotation. This section therefore uses the small
BATF example data bundled with the package rather than the
pseudobulk object above. BATF is an AP-1 family factor and
appears among the motifs identified in the comparisons above.
The example methylation data are derived from ENCODE whole-genome
bisulfite sequencing (ENCSR663MXB, GRCh38). ENCODE data are released
without restrictions. The script that creates them is
inst/scripts/vignette_data.R.
The bundled methylome is a single adult T cell sample from ENCODE,
not one of the subsets above, so it is labelled T cell. The
observed curve uses a T cell colour and the expected curve is grey.
load(system.file("extdata", "BATF_tf_bindsites.rda", package = "methylTFR"))
load(system.file("extdata", "BATF_gcfreqs.rda", package = "methylTFR"))
load(system.file("extdata", "gcdist_BATF.rda", package = "methylTFR"))
load(system.file("extdata", "msites_sub.rda", package = "methylTFR"))
batf_cell_type <- "T cell"
batf_colour <- cell_type_colors[["Th-Mem"]]plotExpectedFootprint() draws two curves: the
methylation observed around the motif, and the level expected from the
GC content of the same windows. The difference between them is the
quantity the deviation score captures.
plotExpectedFootprint(
motif = "BATF",
tf_bindsites = tf_bindsites,
msites = msites_sub,
sample_name = batf_cell_type,
gc_dist = gcdist,
gcfreqs = gcfreqs,
enhancer = NULL,
returnPlotData = FALSE
) +
scale_colour_manual(values = c(
Observed = batf_colour, Expected = "grey55"
))The expected profile is nearly flat here. In this small example, methylation differs little between GC bins (about 0.76 to 0.78), so the GC content of the windows barely changes the expected level. With a genome-wide methylome the bins differ more and the expected profile follows the GC content of the motif.
plotMotifFootprint() combines the two profiles into a
single corrected curve, normalised against the outer flanking windows.
With method = "substraction" the curve is the observed
minus the expected profile; method = "division" uses their
ratio.
plotMotifFootprint(
motif = "BATF",
tf_bindsites = tf_bindsites,
msites = msites_sub,
sample_name = batf_cell_type,
gc_dist = gcdist,
gcfreqs = gcfreqs,
enhancer = NULL,
method = "substraction",
flankNorm = 50
) +
scale_colour_manual(values = batf_colour)
#> Warning: Removed 112 rows containing missing values or values outside the scale range
#> (`geom_line()`).A depression at the motif centre indicates methylation below the level predicted by GC content, which corresponds to a negative deviation score.
Gündüz IB, Wei B, Chen DC, Wang W, Hariharan M, Norell T, Broderick TJ, McClain MT, Satterwhite LL, Burke TW, Petzold EA, Shen X, Woods CW, Fowler VG Jr, Ruffin F, Panuwet P, Barr DB, Wilk AJ, Lee MJ, Blish C, Castellino F, Walley AM, Evans T, Ecker JR, Müller F, Greenleaf WJ. Dissecting epigenome dynamics in human immune cells upon viral and chemical exposure by multimodal single-cell profiling. bioRxiv 2025.09.09.675101. doi: 10.1101/2025.09.09.675101
sessionInfo()
#> R version 4.6.2 (2026-10-29)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 26.04.1 LTS
#>
#> Matrix products: default
#> BLAS: /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3
#> LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.32.so; LAPACK version 3.12.0
#>
#> locale:
#> [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
#> [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
#> [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: Etc/UTC
#> tzcode source: system (glibc)
#>
#> attached base packages:
#> [1] grid stats4 stats graphics grDevices utils datasets
#> [8] methods base
#>
#> other attached packages:
#> [1] circlize_0.4.18 ComplexHeatmap_2.29.0
#> [3] ggplot2_4.0.4 methylTFR_0.99.12
#> [5] SummarizedExperiment_1.43.0 Biobase_2.73.2
#> [7] GenomicRanges_1.65.4 Seqinfo_1.3.2
#> [9] IRanges_2.47.5 S4Vectors_0.51.10
#> [11] BiocGenerics_0.59.13 generics_0.1.4
#> [13] MatrixGenerics_1.25.0 matrixStats_1.5.0
#> [15] data.table_1.18.6.1 BiocStyle_2.41.0
#>
#> loaded via a namespace (and not attached):
#> [1] tidyselect_1.2.1 dplyr_1.2.1 farver_2.1.2
#> [4] R.utils_2.13.0 S7_1.0.0 fastmap_1.2.0
#> [7] digest_0.6.39 lifecycle_1.0.5 cluster_2.1.8.3
#> [10] magrittr_2.0.5 compiler_4.6.2 rlang_1.3.0
#> [13] sass_0.4.10 tools_4.6.2 yaml_2.3.12
#> [16] knitr_1.52 S4Arrays_1.13.3 labeling_0.4.3
#> [19] DelayedArray_0.39.8 RColorBrewer_1.1-3 abind_1.4-8
#> [22] BiocParallel_1.47.0 HDF5Array_1.41.8 withr_3.0.3
#> [25] sys_3.4.3 R.oo_1.27.1 colorspace_2.1-4
#> [28] Rhdf5lib_2.1.1 scales_1.4.0 iterators_1.0.14
#> [31] cli_3.6.6 rmarkdown_2.32 crayon_1.5.3
#> [34] otel_0.3.0 httr_1.4.9 rjson_0.2.23
#> [37] cachem_1.1.0 rhdf5_2.57.20 stringr_1.6.0
#> [40] parallel_4.6.2 BiocManager_1.30.27 XVector_0.53.0
#> [43] vctrs_0.7.3 Matrix_1.7-6 jsonlite_2.0.0
#> [46] GetoptLong_1.1.1 clue_0.3-68 maketools_1.3.2
#> [49] h5mread_1.5.7 foreach_1.5.2 jquerylib_0.1.4
#> [52] glue_1.8.1 codetools_0.2-20 stringi_1.8.9
#> [55] gtable_0.3.6 shape_1.4.6.1 GenomeInfoDb_1.49.3
#> [58] UCSC.utils_1.9.1 tibble_3.3.1 logger_0.4.3
#> [61] pillar_1.11.1 htmltools_0.5.9 rhdf5filters_1.25.5
#> [64] R6_2.6.1 doParallel_1.0.17 evaluate_1.0.5
#> [67] lattice_0.23-1 R.methodsS3_1.8.2 png_0.1-9
#> [70] bslib_0.12.0 SparseArray_1.13.5 xfun_0.62
#> [73] buildtools_1.0.0 pkgconfig_2.0.3 GlobalOptions_0.1.4