# Beta vs M values: which scale to test methylation on # https://pseudocount.com/posts/beta-vs-m-values-methylation/ # # The R code of the post, in the order the page runs it. Run it top to bottom in a fresh # R session. Commented-out blocks are shown on the page but not run there. The package # versions behind the numbers on the page are listed at the end of the post. ## ---- setup ---- suppressPackageStartupMessages({ library(limma) library(ggplot2) }) stopifnot(packageVersion("limma") >= "3.56", packageVersion("ggplot2") >= "3.4.0") pct <- function(x, d = 1) sprintf(paste0("%.", d, "f%%"), 100 * x) dec <- function(x, d = 2) sprintf(paste0("%.", d, "f"), x) num <- function(x) format(round(x), big.mark = ",", scientific = FALSE, trim = TRUE) logit2 <- function(b) log2(b / (1 - b)) # beta value -> M value ilogit2 <- function(m) 2^m / (1 + 2^m) # M value -> beta value violet <- "#5a3fc0"; magenta <- "#d14fa6"; grey <- "#8a8797"; dark <- "#3b3947" theme_pc <- theme_minimal(base_size = 12) + theme(plot.background = element_rect(fill = "white", colour = "white"), panel.grid.minor = element_blank(), legend.position = "bottom", strip.text = element_text(face = "bold")) ## ---- precompute: the page runs simulator, analyse, run, numbers here ---- ## ---- simulator ---- n_cpg <- 20000 # CpGs per data set (array-like mix) n_cpg_even <- 10000 # CpGs per data set in the check with evenly spread means n_per <- 6 # samples per group dm_frac <- 0.10 # share of CpGs that truly differ db_range <- c(0.01, 0.20) # true |delta-beta| of those CpGs, drawn uniformly mean_range <- c(0.02, 0.98) # mean methylation of unchanged CpGs stays inside these edges <- c(0.1, 0.9) # array-like mix: a share of CpGs below edges[1], a share above edges[2], mix_share <- c(0.35, 0.35) # and the rest spread evenly in between dm_bounds <- c(0.01, 0.99) # both group means of a changed CpG stay inside these m_sd <- 0.4 # logit-normal model: typical within-group SD on the M scale phi_med <- 50 # beta model: typical precision (larger = less variable) clip <- 0.001 # beta model: values are clipped to [clip, 1 - clip] before the logit strata_breaks <- c(0, 0.1, 0.3, 0.7, 0.9, 1) strata_labels <- c("0-0.1", "0.1-0.3", "0.3-0.7", "0.7-0.9", "0.9-1") zq <- qnorm(ppoints(200)) # grid for the exact group means under the logit-normal model # mean methylation between lo and hi: array-like (mostly near 0 or 1) or evenly spread draw_mean <- function(lo, hi, mix) { n <- length(lo) if (mix == "even") return(runif(n, lo, hi)) u <- runif(n) low <- runif(n, lo, pmax(lo, edges[1])) high <- runif(n, pmin(hi, edges[2]), hi) between <- pmin(pmax(runif(n, edges[1], edges[2]), lo), hi) ifelse(u < mix_share[1], low, ifelse(u < sum(mix_share), high, between)) } simulate_cpgs <- function(model = c("logit-normal", "beta"), mix = c("array", "even"), n_cpg = 20000) { model <- match.arg(model); mix <- match.arg(mix) is_dm <- seq_len(n_cpg) <= dm_frac * n_cpg db <- ifelse(is_dm, runif(n_cpg, db_range[1], db_range[2]), 0) # centre of the two groups lo <- ifelse(is_dm, dm_bounds[1] + db / 2, mean_range[1]) hi <- ifelse(is_dm, dm_bounds[2] - db / 2, mean_range[2]) mid <- draw_mean(lo, hi, mix) sgn <- sample(c(-1, 1), n_cpg, replace = TRUE) loc_a <- mid - sgn * db / 2 loc_b <- mid + sgn * db / 2 if (model == "logit-normal") { # each CpG gets its own SD on the M scale, scattered around m_sd s <- m_sd * sqrt(10 / rchisq(n_cpg, df = 10)) m_a <- logit2(loc_a); m_b <- logit2(loc_b) M <- cbind(matrix(m_a, n_cpg, n_per), matrix(m_b, n_cpg, n_per)) + matrix(rnorm(n_cpg * 2 * n_per), n_cpg) * s beta <- ilogit2(M) mean_a <- rowMeans(ilogit2(m_a + outer(s, zq))) # true mean beta of each group mean_b <- rowMeans(ilogit2(m_b + outer(s, zq))) } else { # beta distribution with mean loc and precision phi: variance loc (1 - loc) / (1 + phi) phi <- exp(rnorm(n_cpg, log(phi_med), 0.5)) loc <- cbind(matrix(loc_a, n_cpg, n_per), matrix(loc_b, n_cpg, n_per)) beta <- matrix(rbeta(n_cpg * 2 * n_per, loc * phi, (1 - loc) * phi), n_cpg) M <- logit2(pmin(pmax(beta, clip), 1 - clip)) mean_a <- loc_a; mean_b <- loc_b } list(beta = beta, M = M, is_dm = is_dm, true_db = mean_b - mean_a, stratum = cut((mean_a + mean_b) / 2, strata_breaks, labels = strata_labels, include.lowest = TRUE)) } ## ---- analyse ---- group <- factor(rep(c("A", "B"), each = n_per)) design <- model.matrix(~ group) fdr <- 0.05 db_min <- 0.05 # the delta-beta a reader might care about lfc_centre <- 0.5 lfc_M <- logit2(lfc_centre + db_min / 2) - logit2(lfc_centre - db_min / 2) # its M equivalent at 50% # ordinary two-sample t-test (equal variances) for every CpG, from the same linear model ordinary_p <- function(fit) { t <- fit$coefficients[, 2] / (fit$stdev.unscaled[, 2] * fit$sigma) 2 * pt(-abs(t), df = fit$df.residual) } analyse <- function(d) { fit_b <- lmFit(d$beta, design) fit_m <- lmFit(d$M, design) p <- list( "t-test, beta" = ordinary_p(fit_b), "t-test, M" = ordinary_p(fit_m), "limma, beta" = eBayes(fit_b)$p.value[, 2], "limma, M" = eBayes(fit_m)$p.value[, 2], "limma-trend, beta" = eBayes(fit_b, trend = TRUE)$p.value[, 2], "limma-trend, M" = eBayes(fit_m, trend = TRUE)$p.value[, 2], "treat on M" = treat(fit_m, lfc = lfc_M)$p.value[, 2], "treat on beta" = treat(fit_b, lfc = db_min, trend = TRUE)$p.value[, 2]) obs_db <- fit_b$coefficients[, 2] # observed delta-beta, B minus A calls <- lapply(p, function(x) p.adjust(x, "BH") < fdr) calls[["limma, M, then |delta-beta| filter"]] <- calls[["limma, M"]] & abs(obs_db) >= db_min tiny <- abs(d$true_db) < db_min do.call(rbind, lapply(names(calls), function(m) { pv <- if (m %in% names(p)) p[[m]] else p[["limma, M"]] # the filter keeps limma's p-values data.frame(method = m, stratum = strata_labels, null_n = as.vector(tapply(!d$is_dm, d$stratum, sum)), null_p05 = as.vector(tapply(!d$is_dm & pv < 0.05, d$stratum, sum)), dm_n = as.vector(tapply(d$is_dm, d$stratum, sum)), dm_call = as.vector(tapply(d$is_dm & calls[[m]], d$stratum, sum)), big_n = as.vector(tapply(!tiny, d$stratum, sum)), big_call = as.vector(tapply(!tiny & calls[[m]], d$stratum, sum)), call_n = as.vector(tapply(calls[[m]], d$stratum, sum)), call_null = as.vector(tapply(calls[[m]] & !d$is_dm, d$stratum, sum)), call_tiny = as.vector(tapply(calls[[m]] & tiny, d$stratum, sum))) })) } ## ---- run ---- n_sets <- 10 # data sets per variance model and mix set.seed(20260930) runs <- list() for (mix in c("array", "even")) { for (model in c("logit-normal", "beta")) { for (k in seq_len(n_sets)) { d <- simulate_cpgs(model, mix, if (mix == "array") n_cpg else n_cpg_even) if (k == 1 && model == "logit-normal") { if (mix == "array") example_ln <- d else example_even <- d } if (k == 1 && model == "beta" && mix == "array") example_bt <- d runs[[length(runs) + 1]] <- cbind(mix = mix, model = model, set = k, analyse(d)) } } } runs <- do.call(rbind, runs) ## ---- numbers ---- # sums over data sets, by model x method x stratum band_of <- function(st) ifelse(st %in% c("0-0.1", "0.9-1"), "extreme", ifelse(st == "0.3-0.7", "middle", "between")) runs$band <- band_of(runs$stratum) cols <- "cbind(null_n, null_p05, dm_n, dm_call, big_n, big_call, call_n, call_null, call_tiny)" S <- aggregate(as.formula(paste(cols, "~ mix + model + method + stratum")), data = runs, FUN = sum) S$band <- band_of(S$stratum) B <- aggregate(as.formula(paste(cols, "~ mix + model + method + band")), data = S, FUN = sum) Tot <- aggregate(as.formula(paste(cols, "~ mix + model + method")), data = S, FUN = sum) rate <- function(tab, mod, meth, col, den, band = NULL, mx = "array") { keep <- tab$mix == mx & tab$model == mod & tab$method == meth if (!is.null(band)) keep <- keep & tab$band %in% band r <- tab[keep, ] sum(r[[col]]) / sum(r[[den]]) } per_set <- function(mod, meth, mx = "array") sum(Tot$call_n[Tot$mix == mx & Tot$model == mod & Tot$method == meth]) / n_sets # residual SD and prior df, from the first logit-normal data set fb1 <- lmFit(example_ln$beta, design); fm1 <- lmFit(example_ln$M, design) eb1 <- eBayes(fb1); em1 <- eBayes(fm1) sd_beta_ext <- median(fb1$sigma[example_ln$stratum %in% c("0-0.1", "0.9-1")]) sd_beta_mid <- median(fb1$sigma[example_ln$stratum == "0.3-0.7"]) sd_m_ext <- median(fm1$sigma[example_ln$stratum %in% c("0-0.1", "0.9-1")]) sd_m_mid <- median(fm1$sigma[example_ln$stratum == "0.3-0.7"]) d0_beta <- eb1$df.prior; d0_m <- em1$df.prior s0_beta <- sqrt(eb1$s2.prior) ext <- "extreme"; mid <- "middle"; other <- c("middle", "between") t1 <- function(mod, meth, band, mx = "array") rate(B, mod, meth, "null_p05", "null_n", band, mx) pw <- function(mod, meth, band, mx = "array") rate(B, mod, meth, "dm_call", "dm_n", band, mx) tiny_share <- function(mod, meth, band = NULL) { tab <- if (is.null(band)) Tot else B rate(tab, mod, meth, "call_tiny", "call_n", band) } big_power <- function(mod, meth) rate(Tot, mod, meth, "big_call", "big_n") # range of the type I error over the five strata t1_range <- function(mod, meth, mx = "array") { r <- S[S$mix == mx & S$model == mod & S$method == meth, ] range(r$null_p05 / r$null_n) } # Monte Carlo error of a pooled rate, from the spread between data sets (CpGs within a data set # share one estimated prior, so they are not independent) mc_se <- function(mod, meth, bnd, mx = "array") { r <- runs[runs$mix == mx & runs$model == mod & runs$method == meth & runs$band == bnd, ] per <- tapply(r$null_p05, r$set, sum) / tapply(r$null_n, r$set, sum) sd(per) / sqrt(length(per)) } null_mid_n <- sum(B$null_n[B$mix == "array" & B$model == "logit-normal" & B$method == "limma, M" & B$band == mid]) mc_se_max <- max(sapply(c("array", "even"), function(mx) sapply(c("logit-normal", "beta"), function(mod) sapply(c("limma, beta", "limma, M", "limma-trend, beta", "limma-trend, M"), function(meth) sapply(c(ext, mid), function(bnd) mc_se(mod, meth, bnd, mx)))))) t_rng <- range(sapply(c("array", "even"), function(mx) sapply(c("logit-normal", "beta"), function(mod) sapply(c("t-test, beta", "t-test, M"), function(meth) t1_range(mod, meth, mx))))) trend_m_rng <- range(sapply(c("array", "even"), function(mx) sapply(c("logit-normal", "beta"), function(mod) t1_range(mod, "limma-trend, M", mx)))) # how many M units a delta-beta of 0.05 is, near the edge and in the middle dM_at <- function(m) logit2(m + db_min / 2) - logit2(m - db_min / 2) edge_centre <- 0.05 dM_edge <- dM_at(edge_centre); dM_mid <- dM_at(lfc_centre) # the delta-beta that the fixed M threshold lfc_M allows at a mean of m_edge dM_at_db <- function(m, db) logit2(m + db / 2) - logit2(m - db / 2) db_for_lfc <- function(m) uniroot(function(db) dM_at_db(m, db) - lfc_M, c(1e-6, 2 * m - 1e-6))$root m_edge <- 0.03 db_edge_lfc <- db_for_lfc(m_edge) # named scalars quoted in the text; ln = logit-normal model, bt = beta model ln <- "logit-normal"; bt <- "beta" t1_b_ext <- t1(ln, "limma, beta", ext); t1_b_mid <- t1(ln, "limma, beta", mid) t1_m_ext <- t1(ln, "limma, M", ext); t1_m_mid <- t1(ln, "limma, M", mid) pw_b_ext <- pw(ln, "limma, beta", ext); pw_m_ext <- pw(ln, "limma, M", ext) pw_b_mid <- pw(ln, "limma, beta", mid); pw_m_mid <- pw(ln, "limma, M", mid) bt_t1_m_ext <- t1(bt, "limma, M", ext); bt_t1_m_mid <- t1(bt, "limma, M", mid) bt_t1_b_ext <- t1(bt, "limma, beta", ext); bt_t1_b_mid <- t1(bt, "limma, beta", mid) bt_pw_m_ext <- pw(bt, "limma, M", ext); bt_pw_tm_ext <- pw(bt, "limma-trend, M", ext) bt_pw_m_mid <- pw(bt, "limma, M", mid); bt_pw_tm_mid <- pw(bt, "limma-trend, M", mid) trend_b_rng <- range(sapply(c(ln, bt), function(mod) t1_range(mod, "limma-trend, beta"))) tb_t1_ext <- t1(ln, "limma-trend, beta", ext); tb_t1_mid <- t1(ln, "limma-trend, beta", mid) tb_pw_mid <- pw(ln, "limma-trend, beta", mid); tm_pw_mid <- pw(ln, "limma-trend, M", mid) calls_tb_bt <- per_set(bt, "limma-trend, beta") # the check with evenly spread means (ev_) ev_b_ext <- t1(ln, "limma, beta", ext, "even"); ev_b_mid <- t1(ln, "limma, beta", mid, "even") ev_pw_b_ext <- pw(ln, "limma, beta", ext, "even"); ev_pw_m_ext <- pw(ln, "limma, M", ext, "even") ev_bt_m_ext <- t1(bt, "limma, M", ext, "even"); ev_bt_m_mid <- t1(bt, "limma, M", mid, "even") d0_beta_even <- eBayes(lmFit(example_even$beta, design))$df.prior calls_m_ln <- per_set(ln, "limma, M"); calls_t_m_ln <- per_set(ln, "t-test, M") calls_tm_bt <- per_set(bt, "limma-trend, M"); calls_m_bt <- per_set(bt, "limma, M") fdp_rng <- range(sapply(c(ln, bt), function(mod) sapply(c("limma, beta", "limma, M"), function(meth) rate(Tot, mod, meth, "call_null", "call_n")))) calls_t_b_ln <- per_set(ln, "t-test, beta"); calls_b_ln <- per_set(ln, "limma, beta") tiny_m_ext <- tiny_share(ln, "limma, M", ext); tiny_m_oth <- tiny_share(ln, "limma, M", other) tiny_trM_ext <- tiny_share(ln, "treat on M", ext); tiny_trM_oth <- tiny_share(ln, "treat on M", other) filt <- "limma, M, then |delta-beta| filter" tiny_filt <- tiny_share(ln, filt); tiny_trB <- tiny_share(ln, "treat on beta") bt_tiny_filt <- tiny_share(bt, filt); bt_tiny_trB <- tiny_share(bt, "treat on beta") big_filt <- big_power(ln, filt); big_trB <- big_power(ln, "treat on beta") calls_filt <- per_set(ln, filt); calls_trB <- per_set(ln, "treat on beta") calls_trM <- per_set(ln, "treat on M") tiny_b_ext <- tiny_share(ln, "limma, beta", ext) bx <- B[B$mix == "array" & B$model == ln & B$method == "limma, M" & B$band == ext, ] real_tiny_ext <- (bx$call_tiny - bx$call_null) / bx$call_tiny # true change, but below db_min # runs the chunks shown further down, so that the opening can quote their results ## ---- simulator: shown here on the page, run above ---- ## ---- analyse: shown here on the page, run above ---- ## ---- checks ---- # the shortcut t-test above equals t.test() with equal variances x <- example_ln$M[1:5, ] all.equal(unname(ordinary_p(lmFit(x, design))), apply(x, 1, function(r) t.test(r[group == "B"], r[group == "A"], var.equal = TRUE)$p.value)) # limma-trend uses the row means (Amean) as the covariate, and every CpG has the same residual df fm <- lmFit(example_ln$M, design) c(amean_is_rowmean = isTRUE(all.equal(fm$Amean, rowMeans(example_ln$M))), equal_df = length(unique(fm$df.residual)) == 1) ## ---- run: shown here on the page, run above ---- ## ---- numbers: shown here on the page, run above ---- ## ---- fig-type1 ---- show <- c("limma, beta", "limma, M", "limma-trend, beta", "limma-trend, M") f1 <- S[S$mix == "array" & S$method %in% show, ] f1$rate <- f1$null_p05 / f1$null_n f1$model <- factor(ifelse(f1$model == "logit-normal", "logit-normal model (M SD constant)", "beta model (beta precision constant)"), levels = c("logit-normal model (M SD constant)", "beta model (beta precision constant)")) f1$method <- factor(f1$method, levels = show) ggplot(f1, aes(stratum, rate, colour = method, shape = method, group = method)) + geom_hline(yintercept = 0.05, linetype = "dashed", colour = grey) + geom_line(aes(linetype = method), linewidth = 0.8) + geom_point(size = 2.6) + facet_wrap(~ model) + scale_colour_manual(values = c(magenta, violet, "#a3327f", dark), name = NULL) + scale_shape_manual(values = c(16, 17, 1, 2), name = NULL) + scale_linetype_manual(values = c("solid", "solid", "dashed", "dashed"), name = NULL) + scale_y_continuous(labels = function(x) paste0(100 * x, "%")) + labs(x = "true mean methylation of the CpG (beta)", y = "null CpGs with p < 0.05") + guides(colour = guide_legend(nrow = 2), shape = guide_legend(nrow = 2), linetype = guide_legend(nrow = 2)) + theme_pc ## ---- fig-plotsa ---- op <- par(mfrow = c(1, 2), mar = c(4.2, 4.2, 2.2, 1)) plotSA(eBayes(lmFit(example_ln$M, design), trend = TRUE), main = "logit-normal model", xlab = "average M value", pch = 16, cex = 0.3, col = c(grey, magenta)) plotSA(eBayes(lmFit(example_bt$M, design), trend = TRUE), main = "beta model", xlab = "average M value", pch = 16, cex = 0.3, col = c(grey, magenta)) par(op) ## ---- table-power ---- tab <- do.call(rbind, lapply(c("logit-normal", "beta"), function(mod) { do.call(rbind, lapply(c("t-test, beta", "t-test, M", "limma, beta", "limma, M", "limma-trend, beta", "limma-trend, M"), function(meth) { data.frame(model = mod, method = meth, type1_extreme = pct(rate(B, mod, meth, "null_p05", "null_n", "extreme")), type1_middle = pct(rate(B, mod, meth, "null_p05", "null_n", "middle")), power_extreme = pct(rate(B, mod, meth, "dm_call", "dm_n", "extreme"), 0), power_middle = pct(rate(B, mod, meth, "dm_call", "dm_n", "middle"), 0)) })) })) knitr::kable(tab, row.names = FALSE, col.names = c("model", "analysis", "type I error, extremes", "type I error, middle", "power, extremes", "power, middle")) ## ---- fig-hits ---- fit_b <- lmFit(example_ln$beta, design) fit_m <- eBayes(lmFit(example_ln$M, design)) hit <- p.adjust(fit_m$p.value[, 2], "BH") < fdr h <- data.frame(mean_beta = fit_b$Amean[hit], obs_db = fit_b$coefficients[hit, 2], truth = ifelse(abs(example_ln$true_db[hit]) < db_min, paste("true |delta-beta| below", db_min), paste("true |delta-beta|", db_min, "or more"))) n_hits <- nrow(h) n_hits_small <- sum(abs(h$obs_db) < db_min) n_hits_small_edge <- sum(abs(h$obs_db) < db_min & (h$mean_beta < 0.1 | h$mean_beta > 0.9)) ggplot(h, aes(mean_beta, obs_db, colour = truth)) + annotate("rect", xmin = 0, xmax = 1, ymin = -db_min, ymax = db_min, fill = grey, alpha = 0.15) + geom_point(size = 1.6, alpha = 0.8) + scale_colour_manual(values = c(violet, magenta), name = NULL) + labs(x = "average beta value of the CpG", y = "observed delta-beta (B minus A)") + theme_pc ## ---- fig-translate ---- m <- seq(0.03, 0.97, by = 0.005) tr <- data.frame(mean_beta = m, dM = logit2(m + db_min / 2) - logit2(m - db_min / 2)) ggplot(tr, aes(mean_beta, dM)) + geom_hline(yintercept = lfc_M, linetype = "dashed", colour = magenta, linewidth = 0.8) + geom_line(colour = violet, linewidth = 1) + labs(x = "mean methylation (beta)", y = paste("M difference for a delta-beta of", db_min)) + theme_pc ## ---- treat-check ---- # treat() measures its threshold in the units of the coefficient: on a beta-value fit, # lfc = 0.05 is a delta-beta of 0.05. Rebuild its p-values by hand to confirm. tf <- treat(fit_b, lfc = db_min, trend = TRUE) se <- tf$stdev.unscaled[, 2] * sqrt(tf$s2.post) a <- abs(tf$coefficients[, 2]) p_hand <- pt((a - db_min) / se, tf$df.total, lower.tail = FALSE) + pt((a + db_min) / se, tf$df.total, lower.tail = FALSE) all.equal(unname(p_hand), unname(tf$p.value[, 2])) ## ---- practice (shown on the page, not run) ---- # # beta: CpG x sample matrix of beta values; design: your model matrix # b <- pmin(pmax(beta, 0.001), 0.999) # a beta of exactly 0 or 1 has no finite M value # M <- log2(b / (1 - b)) # or the M values from your preprocessing # fit_m <- eBayes(lmFit(M, design), trend = TRUE) # plotSA(fit_m) # flat line: trend = TRUE changes little; curved: keep it # fit_b <- lmFit(beta, design) # same design on beta values: coefficients are delta-beta # res <- data.frame(delta_beta = fit_b$coefficients[, 2], # p_value = fit_m$p.value[, 2], # adj_p = p.adjust(fit_m$p.value[, 2], "BH")) # # only if the claim is "changed by at least 0.05 in beta": # tr <- treat(fit_b, lfc = 0.05, trend = TRUE) # res$adj_p_treat <- p.adjust(tr$p.value[, 2], "BH")