From 8d914e75b1d4c6ae000c08b7f3bd139ae81ae374 Mon Sep 17 00:00:00 2001 From: simonvandekar Date: Sun, 15 Nov 2026 16:17:26 -0600 Subject: [PATCH 1/6] Add mixed-model (lmerMod) RESI confidence intervals - R/resi_mixed_ci.R: asymptotic Var(RESI) from school-level influence values (outcome noise, random design incl. unit counts, sandwich meat, and the variance-component term for the model-based covariance), feeding the existing normal/QF/CF intervals; fast exact CR2 (.mixedCiCR2) used for clubSandwich::vcovCR(type = "CR2") on unweighted lmerMod fits. - resi.lmerMod gains ci.method and ci.design and returns interval columns. - R/mixed_simulations.R: hybridPlasmodeSim() and Lyu-Welsh limit helpers. - Fix the sign of the large-noncentrality branch in .resi_ci_qf. - Mixed point-estimate fixes (n level labels), print rounding, tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- DESCRIPTION | 6 + NAMESPACE | 1 + R/mixed_simulations.R | 361 +++++++++++++++++++++++ R/print.R | 29 +- R/resi.R | 59 +++- R/resi_asymptotic.R | 2 +- R/resi_mixed_ci.R | 285 +++++++++++++++++++ R/resi_pe.R | 139 +-------- R/resi_pe_mixed.R | 378 +++++++++++++++++++++++++ man/designAveragedSe.Rd | 36 +++ man/expectedDesignResi.Rd | 27 ++ man/hybridPlasmodeSim.Rd | 60 ++++ man/lyuLimitResi.Rd | 27 ++ man/resi.Rd | 16 +- man/resi_pe.Rd | 63 ++++- tests/testthat/test-resi-mixed-ci.R | 90 ++++++ tests/testthat/test-resi-mixed-scale.R | 75 +++++ tests/testthat/test-resi.R | 40 +-- tests/testthat/test-resi_asymptotic.R | 6 + 19 files changed, 1510 insertions(+), 190 deletions(-) create mode 100644 R/mixed_simulations.R create mode 100644 R/resi_mixed_ci.R create mode 100644 R/resi_pe_mixed.R create mode 100644 man/designAveragedSe.Rd create mode 100644 man/expectedDesignResi.Rd create mode 100644 man/hybridPlasmodeSim.Rd create mode 100644 man/lyuLimitResi.Rd create mode 100644 tests/testthat/test-resi-mixed-ci.R create mode 100644 tests/testthat/test-resi-mixed-scale.R diff --git a/DESCRIPTION b/DESCRIPTION index 3c66fef..7f3b91e 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -17,6 +17,7 @@ Collate: 'summary.resi.R' 'resi.R' 'resi_pe.R' + 'resi_pe_mixed.R' 'Anova.resi.R' 'data.R' 'chisq2S.R' @@ -36,6 +37,8 @@ Collate: 'print.R' 'omnibus.R' 'simulations.R' + 'mixed_simulations.R' + 'resi_mixed_ci.R' 'resi_asymptotic.R' Imports: aod, @@ -58,6 +61,9 @@ Suggests: glmtoolbox, knitr, lme4, + Matrix, + mlmRev, + numDeriv, pscl, R.rsp, regtools, diff --git a/NAMESPACE b/NAMESPACE index bc0774d..15b7c49 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -55,6 +55,7 @@ export(chisq2S) export(d2S) export(f2S) export(fsq2S) +export(hybridPlasmodeSim) export(insurancePlasmodeSim) export(omnibus) export(resi) diff --git a/R/mixed_simulations.R b/R/mixed_simulations.R new file mode 100644 index 0000000..701b41f --- /dev/null +++ b/R/mixed_simulations.R @@ -0,0 +1,361 @@ +# Mixed-model RESI calibration: Lyu & Welsh (2022) limiting targets and the +# hybrid plasmode simulation for a three-level random-intercept lmer model +# `y ~ X + (1 | school/child)` (developed on mlmRev::egsingle). +# +# Design convention (matches the plasmode): schools are drawn uniformly from +# the observed school profiles and students within a school in proportion to +# the observed school size, so a design with average m students per school +# gives school s a weight m * n_s / mean(n_s). +# +# RESI targets are beta_k / sqrt(n_k Var_kk) (coefficients) and +# sqrt(beta_T' (n_T Var_TT)^{-1} beta_T) (ANOVA terms), with n_k = g schools +# for between-school terms (constant within school, incl. the intercept) and +# n_k = N students for within-school terms, matching resi_pe(level = 2). + +.mixedVarComps <- function(fit, school, child) { + vc <- as.data.frame(lme4::VarCorr(fit)) + list(tau2_school = vc$vcov[vc$grp == school & is.na(vc$var2)], + tau2_child = vc$vcov[vc$grp == child & is.na(vc$var2)], + sigma2 = stats::sigma(fit)^2) +} + +.mixedBetweenColumns <- function(X, school_id) { + vapply(seq_len(ncol(X)), function(j) { + all(tapply(X[, j], school_id, function(x) diff(range(x)) < 1e-10)) + }, logical(1L)) +} + +.mixedFixedTermLabels <- function(fit) { + attr(stats::terms(reformulas::nobars(stats::formula(fit))), "term.labels") +} + +# Per-school sufficient statistics of the GLS information for a three-level +# random-intercept model with the school effect integrated out: +# A_s = sum_j X_j' W_j^{-1} X_j, b_s = sum_j X_j' W_j^{-1} 1, +# c_s = sum_j 1' W_j^{-1} 1, W_j = sigma2 I + tau2_child 11', +# so school s contributes A_s - b_s b_s' / (1 / tau2_school + c_s). +lyuSchoolStats <- function(X, school_id, child_id, tau2_child, sigma2) { + child_id <- droplevels(as.factor(child_id)) + school_of_child <- tapply(as.character(school_id), child_id, `[`, 1L) + T_j <- as.numeric(table(child_id)) + k_j <- tau2_child / (sigma2 + T_j * tau2_child) + sx <- rowsum(X, child_id) + rows <- split(seq_len(nrow(X)), child_id) + schools <- unique(as.character(school_id)) + stats <- lapply(schools, function(s) { + js <- which(school_of_child == s) + A <- Reduce(`+`, lapply(js, function(j) { + Xj <- X[rows[[j]], , drop = FALSE] + (crossprod(Xj) - k_j[j] * tcrossprod(sx[j, ])) / sigma2 + })) + b <- colSums(sx[js, , drop = FALSE] * (1 - k_j[js] * T_j[js])) / sigma2 + c <- sum(T_j[js] * (1 - k_j[js] * T_j[js])) / sigma2 + list(A = A, b = b, c = c, n_child = length(js)) + }) + names(stats) <- schools + stats +} + +.lyuResiTables <- function(beta, V, n, assign, term_labels) { + coef_resi <- beta / sqrt(n * diag(V)) + anova_resi <- vapply(seq_along(term_labels), function(t) { + cols <- which(assign == t) + if (length(unique(n[cols])) != 1L) stop("Term spans between and within blocks: ", term_labels[t]) + Vt <- n[cols[1]] * V[cols, cols, drop = FALSE] + sqrt(drop(crossprod(beta[cols], solve(Vt, beta[cols])))) + }, numeric(1L)) + list(coefficients = data.frame(RESI = coef_resi, row.names = names(beta)), + anova = data.frame(RESI = anova_resi, row.names = term_labels)) +} + +#' Lyu-Welsh limiting RESI for a three-level random-intercept lmer fit +#' +#' Evaluates the g, m -> Inf limit (Lyu & Welsh, 2022) of the per-unit +#' covariance of the fixed effects and the corresponding RESI at the fitted +#' parameters. Between-school columns: n_g Var(beta_b) -> tau2_school C^{-1}, +#' C = g^{-1} sum_s x_s x_s'. Within-school columns: the school intercept acts +#' as a fixed effect, so I_w / N = N^{-1} sum_s (A_s - b_s b_s' / c_s). The +#' between and within blocks are asymptotically independent. +#' @param fit A `lmerMod` fit of `y ~ X + (1 | school/child)`. +#' @param school,child Names of the school and child grouping factors in +#' `lme4::getME(fit, "flist")`. +#' @return List with `coefficients` and `anova` RESI tables, the logical +#' `between` indicator per column, and the per-unit limiting covariance `V`. +#' @keywords internal +lyuLimitResi <- function(fit, school = "schoolid", child = "childid:schoolid") { + X <- lme4::getME(fit, "X") + fl <- lme4::getME(fit, "flist") + vc <- .mixedVarComps(fit, school, child) + beta <- lme4::fixef(fit) + school_id <- fl[[school]] + between <- .mixedBetweenColumns(X, school_id) + Xb <- X[!duplicated(school_id), between, drop = FALSE] + Vb <- vc$tau2_school * solve(crossprod(Xb) / nrow(Xb)) + + st <- lyuSchoolStats(X[, !between, drop = FALSE], school_id, fl[[child]], + vc$tau2_child, vc$sigma2) + N <- sum(vapply(st, `[[`, numeric(1L), "n_child")) + Iw <- Reduce(`+`, lapply(st, function(s) s$A - tcrossprod(s$b) / s$c)) + Vw <- solve(Iw / N) + + V <- matrix(0, ncol(X), ncol(X), dimnames = list(colnames(X), colnames(X))) + V[between, between] <- Vb + V[!between, !between] <- Vw + out <- .lyuResiTables(beta, V, rep(1, ncol(X)), attr(X, "assign"), + .mixedFixedTermLabels(fit)) + out$between <- setNames(between, colnames(X)) + out$V <- V + out +} + +# Information contributions I_s(m) of each observed school profile at +# average m students per school. +.mixedSchoolInfo <- function(fit, m, school, child) { + X <- lme4::getME(fit, "X") + fl <- lme4::getME(fit, "flist") + vc <- .mixedVarComps(fit, school, child) + school_id <- fl[[school]] + st <- lyuSchoolStats(X, school_id, fl[[child]], vc$tau2_child, vc$sigma2) + n_s <- vapply(st, `[[`, numeric(1L), "n_child") + r <- m / mean(n_s) + list(I_s = lapply(st, function(s) { + r * s$A - (r * s$b) %*% t(r * s$b) / (1 / vc$tau2_school + r * s$c) + }), between = .mixedBetweenColumns(X, school_id), X = X) +} + +#' Fixed-m RESI under the expected hybrid plasmode design +#' +#' Exact RESI and per-unit SE when each school profile is represented in +#' proportion to its sampling probability with average `m` students per +#' school (the number of schools g cancels). Converges to [lyuLimitResi()] as +#' m -> Inf; equals `resi_pe(level = 2)` on the observed design at +#' m = mean school size. +#' @inheritParams lyuLimitResi +#' @param m Average number of students per school. +#' @return As [lyuLimitResi()] plus `se_unit`, sqrt(n_k Var_kk). +#' @keywords internal +expectedDesignResi <- function(fit, m, school = "schoolid", child = "childid:schoolid") { + info <- .mixedSchoolInfo(fit, m, school, child) + g <- length(info$I_s) + V <- solve(Reduce(`+`, info$I_s)) + n <- ifelse(info$between, g, m * g) + beta <- lme4::fixef(fit) + out <- .lyuResiTables(beta, V, n, attr(info$X, "assign"), .mixedFixedTermLabels(fit)) + out$se_unit <- setNames(sqrt(n * diag(V)), names(beta)) + out +} + +#' Design-averaged per-unit SE for the hybrid plasmode +#' +#' sqrt(n_k E_X[V(X)]_kk) at g schools and average m students per school, +#' averaging the conditional covariance V(X) = I(X)^{-1} over `n_rep` +#' resampled sets of g school profiles. Because beta-hat is conditionally +#' unbiased this is the finite-(g, m) reference for the Monte Carlo SD of +#' beta-hat; it exceeds `expectedDesignResi()$se_unit` since +#' E[I^{-1}] >= E[I]^{-1}. +#' @inheritParams expectedDesignResi +#' @param g Number of schools. +#' @param n_rep Number of resampled school sets. +#' @keywords internal +designAveragedSe <- function(fit, g, m, n_rep = 2000L, + school = "schoolid", child = "childid:schoolid") { + info <- .mixedSchoolInfo(fit, m, school, child) + v <- replicate(n_rep, tryCatch( + diag(solve(Reduce(`+`, info$I_s[sample.int(length(info$I_s), g, TRUE)]))), + error = function(e) rep(NA_real_, ncol(info$X)))) + n <- ifelse(info$between, g, m * g) + setNames(sqrt(n * rowMeans(v, na.rm = TRUE)), colnames(info$X)) +} + +.mixedSimParams <- function(fit) { + fe <- lme4::fixef(fit) + names(fe) <- paste0("beta_", names(fe)) + vc <- as.data.frame(lme4::VarCorr(fit)) + vc_names <- ifelse(vc$grp == "Residual", "var_Residual", + ifelse(is.na(vc$var2), paste0("var_", vc$grp, "_", vc$var1), + paste0("cov_", vc$grp, "_", vc$var1, "_", vc$var2))) + c(fe, setNames(vc$vcov, vc_names)) +} + +.hybridResiSummary <- function(reps, truth_resi, settings) { + sources <- list(coefficients = "resi_coef", anova = "resi_anova") + do.call(rbind, unlist(lapply(names(sources), function(table_name) { + rep_name <- sources[[table_name]] + truth <- truth_resi[[table_name]] + lapply(rownames(truth), function(term) { + values <- vapply(reps, function(rep) rep[[rep_name]][term, "RESI"], numeric(1L)) + replicate_n <- vapply(reps, function(rep) rep[[rep_name]][term, "n"], numeric(1L)) + first <- reps[[1L]][[rep_name]][term, , drop = FALSE] + data.frame( + as.list(settings), table = table_name, term = term, + n = mean(replicate_n), n_sd = stats::sd(replicate_n), + variation_level = first$`Variation level`, + n_level = first$`n level`, + truth_resi = truth[term, "RESI"], + mc_mean_resi = mean(values, na.rm = TRUE), + bias_resi = truth[term, "RESI"] - mean(values, na.rm = TRUE), + mc_sd_resi = stats::sd(values, na.rm = TRUE), + mc_se_resi = stats::sd(values, na.rm = TRUE) / sqrt(sum(is.finite(values))), + n_success = sum(is.finite(values)), + check.names = FALSE, row.names = NULL) + }) + }), recursive = FALSE)) +} + +#' Hybrid plasmode calibration simulation for three-level mixed-model RESI +#' +#' Fits `formula` (ML) to `data` and treats the fitted fixed effects and +#' variance components as the data-generating truth. Each replicate +#' (i) resamples `n_schools` school covariate profiles with replacement and, +#' within each, students with replacement in proportion to the observed school +#' size so that the average is `n_per_site`; (ii) draws school and student +#' random effects with replacement from the BLUP pools, each centred and +#' rescaled to the fitted variance component, plus Gaussian residuals; +#' (iii) refits by REML and computes `resi_pe(level = 2)` with the model-based +#' covariance. RESI and per-unit SE targets are the Lyu-Welsh g, m -> Inf +#' limit at the full-data ML estimates ([lyuLimitResi()]). +#' +#' @param formula Model formula of the form `y ~ X + (1 | school/child)`. +#' @param data Data frame containing the variables in `formula`. +#' @param school,child Names of the school and child id columns of `data`. +#' @param n_schools,n_per_site Vectors crossed to form the simulation grid. +#' @param nsim Number of replicates per grid cell. +#' @param mc.cores Number of cores for [parallel::mclapply()] over replicates. +#' @param seed Seed (with the "L'Ecuyer-CMRG" generator) for reproducibility. +#' @param control `lme4::lmerControl()` used for all fits. +#' @param rep_fun Optional `function(fit, design)` evaluated on each replicate +#' fit; its return value is stored as `extra` in the replicate output. +#' @param keep_reps Logical; return the per-replicate output. +#' @return A list with `summary` (parameter-level calibration per cell), +#' `resi_summary` (RESI calibration per cell and term), `truth_fit`, +#' `truth_resi`, and optionally `reps` (per cell). +#' @export +hybridPlasmodeSim <- function(formula, data, school = "schoolid", child = "childid", + n_schools = c(15, 30, 60, 100), + n_per_site = c(25, 100, 200), + nsim = 1000L, mc.cores = 1L, seed = 2026, + control = lme4::lmerControl(optimizer = "bobyqa", + optCtrl = list(maxfun = 2e5)), + rep_fun = NULL, keep_reps = !is.null(rep_fun)) { + data <- as.data.frame(data) + data[[school]] <- factor(data[[school]]) + data[[child]] <- factor(data[[child]]) + school_grp <- school + child_grp <- paste0(child, ":", school) + response <- all.vars(formula[[2L]]) + fixed_rhs <- stats::delete.response(stats::terms(reformulas::nobars(formula))) + + truth_fit <- lme4::lmer(formula, data = data, REML = FALSE, control = control) + true_params <- .mixedSimParams(truth_fit) + truth_resi <- lyuLimitResi(truth_fit, school_grp, child_grp) + beta <- lme4::fixef(truth_fit) + vc <- .mixedVarComps(truth_fit, school_grp, child_grp) + resid_sd <- stats::sigma(truth_fit) + + # BLUP pools centred to mean zero and rescaled so their (1/G) variance equals + # the fitted component, undoing BLUP shrinkage; draws are with replacement. + rescale_blup <- function(blup, target_var) { + centered <- blup - mean(blup) + centered * sqrt(target_var / mean(centered^2)) + } + re <- lme4::ranef(truth_fit) + school_pool <- rescale_blup(re[[school_grp]][[1L]], vc$tau2_school) + child_pool <- rescale_blup(re[[child_grp]][[1L]], vc$tau2_child) + + school_profiles <- levels(data[[school]]) + rows_by_school <- split(seq_len(nrow(data)), data[[school]]) + children_by_school <- lapply(rows_by_school, function(idx) unique(as.character(data[[child]][idx]))) + rows_by_child <- split(seq_len(nrow(data)), as.character(data[[child]])) + mean_site_size <- mean(lengths(children_by_school)) + + sample_design <- function(g, m) { + source_schools <- sample(school_profiles, g, replace = TRUE) + pieces <- lapply(seq_len(g), function(s) { + child_ids <- children_by_school[[source_schools[s]]] + k <- max(1L, as.integer(round(m * length(child_ids) / mean_site_size))) + selected <- sample(child_ids, k, replace = TRUE) + idx <- rows_by_child[selected] + list(rows = unlist(idx, use.names = FALSE), + child = rep(paste0(s, "_", seq_len(k)), lengths(idx)), + school = rep(as.character(s), sum(lengths(idx)))) + }) + design <- data[unlist(lapply(pieces, `[[`, "rows")), , drop = FALSE] + # Levels in order of appearance: random effects are indexed by level code. + school_ids <- unlist(lapply(pieces, `[[`, "school")) + child_ids <- unlist(lapply(pieces, `[[`, "child")) + design[[school]] <- factor(school_ids, levels = unique(school_ids)) + design[[child]] <- factor(child_ids, levels = unique(child_ids)) + rownames(design) <- NULL + design + } + + generate_outcome <- function(design) { + school_effect <- sample(school_pool, nlevels(design[[school]]), replace = TRUE) + child_effect <- sample(child_pool, nlevels(design[[child]]), replace = TRUE) + fixed_part <- stats::model.matrix(fixed_rhs, data = design) %*% beta + drop(fixed_part) + school_effect[design[[school]]] + child_effect[design[[child]]] + + stats::rnorm(nrow(design), sd = resid_sd) + } + + fe_names <- paste0("beta_", names(beta)) + between <- truth_resi$between + # Lyu-Welsh per-unit SE reference sqrt(n_k V_kk). + truth_se_unit <- setNames(sqrt(diag(truth_resi$V)), fe_names) + param_names <- names(true_params) + is_fe <- param_names %in% fe_names + + grid <- expand.grid(n_schools = n_schools, n_per_site = n_per_site) + RNGkind("L'Ecuyer-CMRG") + set.seed(seed) + rows <- resi_rows <- all_reps <- vector("list", nrow(grid)) + for (cell in seq_len(nrow(grid))) { + g <- grid$n_schools[cell] + m <- grid$n_per_site[cell] + reps <- parallel::mclapply(seq_len(nsim), function(i) { + design <- sample_design(g, m) + design[[response]] <- generate_outcome(design) + fit <- tryCatch(suppressWarnings(suppressMessages( + lme4::lmer(formula, data = design, REML = TRUE, control = control))), + error = function(e) NULL) + if (is.null(fit)) return(NULL) + point <- resi_pe(fit, anova = TRUE, vcovfunc = stats::vcov, level = 2) + list(params = .mixedSimParams(fit), + fe_se = setNames(sqrt(diag(as.matrix(stats::vcov(fit)))), fe_names), + resi_coef = point$coefficients, resi_anova = point$anova, + extra = if (!is.null(rep_fun)) rep_fun(fit, design)) + }, mc.cores = mc.cores, mc.set.seed = TRUE) + reps <- Filter(Negate(is.null), reps) + + param_mat <- do.call(rbind, lapply(reps, function(r) r$params[param_names])) + mc_mean <- colMeans(param_mat, na.rm = TRUE) + mc_sd <- apply(param_mat, 2L, stats::sd, na.rm = TRUE) + mean_model_se <- colMeans(do.call(rbind, lapply(reps, function(r) r$fe_se[fe_names])), na.rm = TRUE) + n_scaling <- setNames(ifelse(between, g, g * m), fe_names) + mc_sd_unit <- mc_sd[fe_names] * sqrt(n_scaling) + + rows[[cell]] <- data.frame( + n_schools = g, n_per_site = m, n_success = length(reps), + param = param_names, + truth = true_params[param_names], + mc_mean = mc_mean[param_names], + bias = true_params[param_names] - mc_mean[param_names], + mc_sd = mc_sd[param_names], + mean_model_se = ifelse(is_fe, mean_model_se[param_names], NA_real_), + se_ratio = ifelse(is_fe, mean_model_se[param_names] / mc_sd[param_names], NA_real_), + se_n_level = ifelse(is_fe, ifelse(between[match(param_names, fe_names)], "schools", "students"), NA), + n_scaling = unname(n_scaling[param_names]), + truth_se_scaled = unname(truth_se_unit[param_names]), + mc_error_sd_scaled = unname(mc_sd_unit[param_names]), + scaled_mc_error_sd_ratio = unname(mc_sd_unit[param_names] / truth_se_unit[param_names]), + row.names = NULL, stringsAsFactors = FALSE) + resi_rows[[cell]] <- .hybridResiSummary(reps, truth_resi, + list(n_schools = g, n_per_site = m)) + if (keep_reps) all_reps[[cell]] <- reps + message("Finished cell ", cell, "/", nrow(grid), ": n_schools = ", g, + ", n_per_site = ", m, " (", length(reps), " successful fits)") + } + out <- list(summary = do.call(rbind, rows), resi_summary = do.call(rbind, resi_rows), + truth_fit = truth_fit, truth_resi = truth_resi, grid = grid) + if (keep_reps) out$reps <- all_reps + out +} diff --git a/R/print.R b/R/print.R index 0a26837..20a63dd 100644 --- a/R/print.R +++ b/R/print.R @@ -1,3 +1,20 @@ +# Round only numeric columns so tables with character columns (e.g. the +# mixed-model `Term` and `Variation level`) can be printed. +# print.anova mangles character columns, so such anova tables are printed as +# plain data frames after their heading. +.roundNumeric <- function(x, digits) { + if (!is.data.frame(x)) return(round(x, digits = digits)) + num <- vapply(x, is.numeric, logical(1L)) + if (all(num)) return(round(x, digits = digits)) + if (inherits(x, "anova")) { + if (!is.null(attr(x, "heading"))) cat(attr(x, "heading"), sep = "\n") + attr(x, "heading") <- NULL + class(x) <- "data.frame" + } + x[num] <- lapply(x[num], round, digits = digits) + x +} + #' @export print.resi <- function(x, digits = max(3L, getOption("digits") - 3L), ...) { cat("\nAnalysis of effect sizes based on RESI:") @@ -14,20 +31,20 @@ print.resi <- function(x, digits = max(3L, getOption("digits") - 3L), ...) { # coefficients table if (!is.null(x$coefficients)){ cat("\nCoefficient Table \n") - print(round(x$coefficients, digits = digits)) + print(.roundNumeric(x$coefficients, digits = digits)) } # anova table if (!is.null(x$anova)){ cat("\n\n") - print(round(x$anova, digits = digits)) + print(.roundNumeric(x$anova, digits = digits)) } # overall if (!(is.null(x$overall))){ if (is.null(x$model.reduced$formula)){ cat("\nOverall RESI comparing model to intercept-only model:\n\n") - print(round(x$overall, digits = digits)) + print(.roundNumeric(x$overall, digits = digits)) } else{ if ((x$model.reduced$formula == as.formula(paste(format(formula(x$model.full)[[2]]), "~ 1")))){ cat("\nOverall RESI comparing model to intercept-only model:\n\n") @@ -37,7 +54,7 @@ print.resi <- function(x, digits = max(3L, getOption("digits") - 3L), ...) { overall = as.data.frame(x$overall) overall = overall[nrow(overall),] rownames(overall) = NULL - print(round(overall, digits = digits)) + print(.roundNumeric(overall, digits = digits)) } } @@ -70,7 +87,7 @@ print.summary_resi <- function(x, digits = max(3L, getOption("digits") - 3L), .. cat("\nConfidence level = ", x$alpha) cat("\nCall: ", paste(deparse(x$model.full$call), sep = "\n", collapse = "\n"), "\n",sep = "") cat("\nCoefficient Table \n") - print(round(x$coefficients, digits = digits)) + print(.roundNumeric(x$coefficients, digits = digits)) invisible(x) } @@ -78,7 +95,7 @@ print.summary_resi <- function(x, digits = max(3L, getOption("digits") - 3L), .. print.omnibus_resi <- function(x, digits = max(3L, getOption("digits") - 3L), ...) { cat("\nAnalysis of effect sizes based on RESI:") cat("\nConfidence level = ", x$alpha, "\n") - print(round(x$overall, digits = digits)) + print(.roundNumeric(x$overall, digits = digits)) invisible(x) } diff --git a/R/resi.R b/R/resi.R index 396367d..ef7e521 100644 --- a/R/resi.R +++ b/R/resi.R @@ -752,14 +752,65 @@ resi.lme = function(model.full, alpha = 0.05, nboot = 1000, anova = TRUE, vcovfu return(output) } -#' @describeIn resi RESI point and interval estimation for lmerMod models +#' @describeIn resi RESI point and asymptotic interval estimation for lmerMod +#' models whose random effects are nested in an outermost cluster. CIs use +#' cluster-level influence functions (`ci.method` one of `"normal"`, `"qf"`, +#' `"cf"`; coefficients get the signed normal CI for `"qf"`). Use +#' `vcovfunc = stats::vcov` for model-based or `clubSandwich::vcovCR` (e.g. +#' `vcov.args = list(type = "CR2")`) for cluster-robust intervals. +#' `ci.design = TRUE` (default) treats the cluster covariate profiles as +#' sampled; `FALSE` gives intervals conditional on the observed design. +#' `ci.method = "none"` returns point estimates only. ANOVA CIs are for the +#' joint Wald test of each term's columns (Type II without interactions). +#' @param ci.design Logical; for `lmerMod` CIs, include the variability of +#' the cluster-level design. #' @export resi.lmerMod = function(model.full, alpha = 0.05, nboot = 1000, anova = TRUE, - vcovfunc = clubSandwich::vcovCR, vcov.args = list(), ...){ - warning("\nConfidence Interval procedure not developed for lmerMod, returning point estimates only") + vcovfunc = clubSandwich::vcovCR, vcov.args = list(), + ci.method = c("normal", "qf", "cf", "none"), + ci.design = TRUE, ...){ + ci.method <- match.arg(ci.method) + dots <- list(...) + robust <- !identical(vcovfunc, stats::vcov) + pe_vcovfunc <- vcovfunc + if (ci.method != "none" && robust) { + design <- .resiMixedModelDesign(model.full, "lmerMod") + Vhat <- .resiMixedVcov(model.full, vcovfunc, vcov.args, + .resiMixedCluster(dots$cluster, design, model.full, "lmerMod"))(model.full) + pe_vcovfunc <- function(object, ...) Vhat + } output = list(alpha = alpha, nboot = 0) - output = c(output, resi_pe(model.full, vcovfunc = vcovfunc, vcov.args = vcov.args, anova = anova, ...)) # RESI point estimates + output = c(output, resi_pe(model.full, vcovfunc = pe_vcovfunc, vcov.args = vcov.args, anova = anova, ...)) # RESI point estimates output$boot.method = "nonparam" + if (ci.method != "none") { + if (!robust) Vhat <- as.matrix(stats::vcov(model.full)) + ci_cluster <- dots$cluster + if (!is.null(ci_cluster) && !(is.character(ci_cluster) && length(ci_cluster) == 1L)) ci_cluster <- NULL + cis <- .resi_ci_mixed(model.full, Vhat, robust, + n_coef = setNames(output$coefficients$n, rownames(output$coefficients)), + n_anova = if (anova) setNames(output$anova$n, rownames(output$anova)), + ci.method = ci.method, alpha = alpha, design = ci.design, + cluster = ci_cluster, + n_level_coef = setNames(output$coefficients$`n level`, rownames(output$coefficients)), + n_level_anova = if (anova) setNames(output$anova$`n level`, rownames(output$anova)))[[ci.method]] + ci_cols <- paste0(sort(c(alpha / 2, 1 - alpha / 2)) * 100, "%") + pos <- match("RESI", names(output$coefficients)) + output$coefficients <- cbind(output$coefficients[seq_len(pos)], + setNames(as.data.frame(cis$coefficients), ci_cols), + output$coefficients[-seq_len(pos)]) + if (anova) { + anova_class <- class(output$anova) + pos <- match("RESI", names(output$anova)) + anova_df <- as.data.frame(output$anova) + output$anova <- cbind(anova_df[seq_len(pos)], + setNames(as.data.frame(cis$anova), ci_cols), + anova_df[-seq_len(pos)]) + class(output$anova) <- anova_class + } + output$ci.method <- ci.method + } else { + warning("\nci.method = 'none': returning point estimates only") + } class(output) = "resi" return(output) } diff --git a/R/resi_asymptotic.R b/R/resi_asymptotic.R index 9b9c224..c77b82f 100644 --- a/R/resi_asymptotic.R +++ b/R/resi_asymptotic.R @@ -595,7 +595,7 @@ if (q > 1e4 || nc > 1e4) { sq <- sqrt(max(q, 0)) snc <- sqrt(max(nc, 0)) - return(pnorm(snc - sq, lower.tail = FALSE) + pnorm(-snc - sq)) + return(pnorm(snc - sq) + pnorm(-snc - sq)) } pchisq(q, df = 1, ncp = nc, lower.tail = FALSE) } diff --git a/R/resi_mixed_ci.R b/R/resi_mixed_ci.R new file mode 100644 index 0000000..ec62206 --- /dev/null +++ b/R/resi_mixed_ci.R @@ -0,0 +1,285 @@ +# Asymptotic RESI confidence intervals for lmerMod fits with random effects +# nested in an outermost cluster (derivation: AIgams notes/resi_mixed_ci.qmd). +# +# Var(R_hat) is estimated from school-level (outermost-cluster) influence +# contributions: (a) outcome noise through beta_hat, (b) sampling of the +# per-cluster information I_s (random design), (c) sampling of the meat +# U_s U_s' (robust covariance only), plus, for the model-based covariance, +# (psi) the variance-component uncertainty. The resulting contrast lists are +# passed to the CI functions in resi_asymptotic.R. + +# Marginal-covariance quantities for theta (lme4 relative covariance +# parameters) and sigma. V = sigma^2 (I + Z Lambda Lambda' Z'), handled by +# Woodbury with M = Lambda' Z' Z Lambda + I. +.mixedCiGls <- function(base, theta, sigma) { + Lt <- base$Lambdat + Lt@x <- theta[base$Lind] + LZt <- Lt %*% base$Zt + ch <- Matrix::Cholesky(Matrix::tcrossprod(LZt), perm = TRUE, LDL = FALSE, Imult = 1) + vinv <- function(B) { + as.matrix(B - Matrix::crossprod(LZt, Matrix::solve(ch, LZt %*% B, system = "A"))) + } + VX <- vinv(base$X) + XVX <- crossprod(base$X, VX) + beta <- drop(solve(XVX, crossprod(VX, base$y))) + r <- drop(base$y - base$X %*% beta) + list(VX = VX / sigma^2, info = XVX / sigma^2, beta = beta, r = r, + rVr = sum(r * drop(vinv(r))), + logdetM = 2 * as.numeric(Matrix::determinant(ch, sqrt = TRUE)$modulus), + logdetXVX = as.numeric(determinant(XVX)$modulus)) +} + +.mixedCiDeviance <- function(base, psi) { + k <- length(psi) + gls <- .mixedCiGls(base, psi[-k], psi[k]) + N <- length(base$y); p <- ncol(base$X); s2 <- psi[k]^2 + if (base$REML) { + (N - p) * log(2 * pi * s2) + gls$logdetM + gls$logdetXVX + gls$rVr / s2 + } else { + N * log(2 * pi * s2) + gls$logdetM + gls$rVr / s2 + } +} + +.mixedCiBase <- function(fit, cluster) { + fl <- lme4::getME(fit, "flist") + if (is.null(cluster)) cluster <- names(fl)[which.min(vapply(fl, nlevels, integer(1L)))] + cl <- if (length(cluster) == 1L && cluster %in% names(fl)) fl[[cluster]] else cluster + cl <- droplevels(as.factor(cl)) + Zt <- lme4::getME(fit, "Zt") + zt <- methods::as(Zt, "TsparseMatrix") + if (any(tapply(as.integer(cl)[zt@j + 1L], zt@i, function(x) length(unique(x))) > 1L)) { + stop("Mixed-model RESI CIs require every random effect to be nested within `cluster`.") + } + list(X = lme4::getME(fit, "X"), y = lme4::getME(fit, "y"), Zt = Zt, + Lambdat = lme4::getME(fit, "Lambdat"), Lind = lme4::getME(fit, "Lind"), + theta = lme4::getME(fit, "theta"), sigma = stats::sigma(fit), + REML = lme4::isREML(fit), cluster = cl) +} + +# Per-cluster information contributions I_s (g x p^2) and scores U_s (g x p). +.mixedCiClusterPieces <- function(base, gls) { + X <- base$X; p <- ncol(X) + prods <- do.call(cbind, lapply(seq_len(p), function(b) X * gls$VX[, b])) + list(I_s = rowsum(prods, base$cluster), + U_s = rowsum(gls$VX * gls$r, base$cluster)) +} + +# CR2 cluster-robust covariance (Pustejovsky & Tipton, 2018) with working +# covariance V, matching clubSandwich::vcovCR(fit, type = "CR2") for lmerMod +# fits with random effects nested in `cluster`, without its n_s x n_s matrix +# roots. clubSandwich adjusts W_s e_s by A_s = V_s^{1/2} G_s^{-1/2} V_s^{1/2}, +# G_s = V_s^{1/2} (V_s - X_s M X_s') V_s^{1/2}. With V_s = sigma^2 (I + Z_s Z_s') +# (Z_s = rows of Z Lambda) and P = V_s^{-1/2} X_s chol(M)', G_s = V_s (I - P P') V_s +# equals sigma^4 I off span(Z_s, P), so its inverse root is computed in that +# small invariant subspace. +.mixedCiCR2 <- function(fit, cluster = NULL) { + base <- .mixedCiBase(fit, cluster) + gls <- .mixedCiGls(base, base$theta, base$sigma) + M <- solve(gls$info) + Cm <- chol(M) + s2 <- base$sigma^2 + LZ <- Matrix::t(base$Lambdat %*% base$Zt) + rows <- split(seq_along(base$y), base$cluster) + u <- vapply(rows, function(idx) { + Zs <- LZ[idx, , drop = FALSE] + Zs <- as.matrix(Zs[, Matrix::colSums(Zs != 0) > 0, drop = FALSE]) + # Thin left singular vectors of Zs via the small q_s x q_s eigenproblem + # (LAPACK dgesdd occasionally fails to converge on these matrices). + ez <- eigen(crossprod(Zs), symmetric = TRUE) + keep <- ez$values > max(ez$values) * 1e-12 + sv <- list(d = sqrt(ez$values[keep])) + sv$u <- Zs %*% (ez$vectors[, keep, drop = FALSE] %*% diag(1 / sv$d, length(sv$d))) + vpow <- function(B, a) { + base$sigma^(2 * a) * (B + sv$u %*% (((1 + sv$d^2)^a - 1) * crossprod(sv$u, B))) + } + VmhX <- vpow(base$X[idx, , drop = FALSE], -0.5) + P <- VmhX %*% t(Cm) + Tq <- qr.Q(qr(cbind(sv$u, P))) + TU <- crossprod(Tq, sv$u) + TVT <- s2 * (diag(ncol(Tq)) + TU %*% (sv$d^2 * t(TU))) + TP <- crossprod(Tq, P) + eg <- eigen(TVT %*% (diag(ncol(Tq)) - tcrossprod(TP)) %*% TVT, symmetric = TRUE) + Gmh <- eg$vectors %*% (t(eg$vectors) / sqrt(pmax(eg$values, .Machine$double.eps))) + h <- vpow(matrix(gls$r[idx]), 0.5) + Th <- crossprod(Tq, h) + drop(crossprod(VmhX, (h - Tq %*% Th) / s2^2 + Tq %*% (Gmh %*% Th))) + }, numeric(ncol(base$X))) + out <- M %*% tcrossprod(u) %*% M + dimnames(out) <- list(colnames(base$X), colnames(base$X)) + out +} + +# Directional derivative of R = Sigma^{-1/2} b with respect to Sigma in +# direction dSigma, via the Lyapunov solution for d(Sigma^{1/2}). +.mixedCiDR <- function(eig, R, dSigma) { + sq <- sqrt(eig$values) + V <- eig$vectors + M <- crossprod(V, dSigma %*% V) + dHalf <- V %*% (M / outer(sq, sq, `+`)) %*% t(V) + # d(Sigma^{-1/2}) = -Sigma^{-1/2} d(Sigma^{1/2}) Sigma^{-1/2} + ihalf <- V %*% (t(V) / sq) + -drop(ihalf %*% dHalf %*% R) +} + +.mixedCiContrast <- function(L, n_k, beta, Vhat, Itot, pieces, robust, + design, counts = NULL, Jpsi = NULL, Vpsi = NULL) { + m1 <- nrow(L) + Sigma <- n_k * L %*% Vhat %*% t(L) + Sigma <- (Sigma + t(Sigma)) / 2 + eig <- eigen(Sigma, symmetric = TRUE) + ihalf <- eig$vectors %*% (t(eig$vectors) / sqrt(eig$values)) + R <- drop(ihalf %*% L %*% beta) + p <- ncol(L); g <- nrow(pieces$U_s) + Iinv <- solve(Itot) + Ibar <- Itot / g + Bbar <- crossprod(pieces$U_s) / g + # n_k is itself a sum of per-cluster unit counts when it counts units below + # the cluster level, so it moves with the cluster information. + LVL <- L %*% Vhat %*% t(L) + dcounts <- if (design && !is.null(counts)) counts - mean(counts) else rep(0, g) + d <- t(vapply(seq_len(g), function(s) { + U <- pieces$U_s[s, ] + out <- if (robust) drop(ihalf %*% L %*% (Iinv %*% U)) else rep(0, m1) + dV <- matrix(0, p, p) + if (design) { + dI <- matrix(pieces$I_s[s, ], p, p) - Ibar + dV <- if (robust) -Iinv %*% dI %*% Vhat - Vhat %*% dI %*% Iinv else -Iinv %*% dI %*% Iinv + } + if (robust) dV <- dV + Iinv %*% (tcrossprod(U) - Bbar) %*% Iinv + if (design || robust) { + out <- out + .mixedCiDR(eig, R, n_k * L %*% dV %*% t(L) + dcounts[s] * LVL) + } + out + }, numeric(m1))) + if (m1 == 1L) d <- matrix(d, ncol = 1L) + d <- d * sqrt(g / (g - 1)) + var_R <- crossprod(d) + if (!robust) var_R <- var_R + diag(m1) / n_k + if (!is.null(Jpsi)) var_R <- var_R + Jpsi %*% Vpsi %*% t(Jpsi) + var_R <- (var_R + t(var_R)) / 2 + # Influence values for the signed Cornish-Fisher skewness (m1 = 1). For the + # model-based covariance, the outcome-noise term uses the cluster scores. + phi <- NULL + if (m1 == 1L) { + phi_d <- if (robust) drop(d) else + drop(d) + sqrt(g / (g - 1)) * drop(pieces$U_s %*% (Iinv %*% t(ihalf %*% L))) + phi <- g * phi_d + } + list(m1 = m1, n = n_k, R_beta = R, Stilde = sqrt(sum(R^2)), + Sigma_R = n_k * var_R, var_R = var_R, phi_tilde = phi, g = g) +} + +.mixedCiInterval <- function(contrast, ci.method, alpha, signed) { + if (signed) { + if (ci.method == "cf") { + cf <- contrast + cf$n <- contrast$g + cf$Sigma_R <- contrast$g * contrast$var_R + return(.resi_ci_cf_signed(cf, alpha)) + } + return(.resi_ci_normal_signed(contrast, alpha)) + } + switch(ci.method, + normal = .resi_ci_normal_unsigned(contrast, alpha), + qf = .resi_ci_qf(contrast, alpha), + cf = .resi_ci_cf(contrast, alpha)) +} + +#' Mixed-model RESI confidence intervals (internal) +#' +#' Computes asymptotic CIs for the coefficient (signed) and ANOVA (unsigned) +#' RESI of an `lmerMod` fit, for terms normalized by `n_coef`/`n_anova`. +#' @param fit `lmerMod` fit whose random effects are nested in `cluster`. +#' @param Vhat Covariance of the fixed effects used for the point estimates. +#' @param robust Logical; `Vhat` is a cluster-robust sandwich. +#' @param n_coef,n_anova Named term-specific normalizing counts. +#' @param ci.method One of `"normal"`, `"qf"`, `"cf"` (coefficients use the +#' signed normal CI for `"qf"`). +#' @param design Logical; include the design (cluster information) sampling +#' term, i.e. treat the cluster covariate profiles as random. +#' @param cluster Name of the outermost grouping factor. +#' @param n_level_coef,n_level_anova Optional named grouping-factor names +#' whose counts are `n_coef`/`n_anova` (the `n level` columns). +#' @return A list with, for each requested `ci.method`, `coefficients` and +#' `anova` matrices of LCI and UCI, and `se`, the estimated SD of each +#' one-degree-of-freedom RESI estimate. +#' @keywords internal +#' @noRd +.resi_ci_mixed <- function(fit, Vhat, robust, n_coef, n_anova = NULL, + ci.method = c("normal", "qf", "cf"), alpha = 0.05, + design = TRUE, cluster = NULL, + n_level_coef = NULL, n_level_anova = NULL) { + ci.method <- match.arg(ci.method, several.ok = TRUE) + base <- .mixedCiBase(fit, cluster) + gls <- .mixedCiGls(base, base$theta, base$sigma) + pieces <- .mixedCiClusterPieces(base, gls) + beta <- lme4::fixef(fit) + Vhat <- as.matrix(Vhat)[names(beta), names(beta)] + p <- length(beta) + assign <- attr(base$X, "assign") + terms <- .mixedFixedTermLabels(fit) + fl <- lme4::getME(fit, "flist") + unit_counts <- function(n_k, lev) { + if (n_k == nlevels(base$cluster)) return(NULL) + if (is.null(lev) || !(lev %in% names(fl))) { + lev <- names(fl)[vapply(fl, nlevels, integer(1L)) == n_k] + if (length(lev) != 1L) return(NULL) + } + as.numeric(tapply(as.character(fl[[lev]]), base$cluster, + function(x) length(unique(x)))) + } + contrasts <- c( + lapply(seq_len(p), function(j) { + nm <- names(beta)[j] + list(L = diag(p)[j, , drop = FALSE], n = n_coef[[nm]], + counts = unit_counts(n_coef[[nm]], n_level_coef[nm])) + }), + if (!is.null(n_anova)) lapply(names(n_anova), function(t) { + list(L = diag(p)[assign == match(t, terms), , drop = FALSE], n = n_anova[[t]], + counts = unit_counts(n_anova[[t]], n_level_anova[t])) + })) + + Jpsi_all <- NULL + if (!robust) { + psi_hat <- c(base$theta, base$sigma) + Rfun <- function(psi) { + k <- length(psi) + V <- solve(.mixedCiGls(base, psi[-k], psi[k])$info) + unlist(lapply(contrasts, function(cn) { + S <- cn$n * cn$L %*% V %*% t(cn$L) + e <- eigen((S + t(S)) / 2, symmetric = TRUE) + drop(e$vectors %*% (t(e$vectors) / sqrt(e$values)) %*% cn$L %*% beta) + })) + } + Jpsi_all <- numDeriv::jacobian(Rfun, psi_hat) + H <- numDeriv::hessian(function(psi) .mixedCiDeviance(base, psi), psi_hat) + eh <- eigen((H + t(H)) / 2, symmetric = TRUE) + keep <- eh$values > max(eh$values) * 1e-8 + Vpsi <- 2 * eh$vectors[, keep, drop = FALSE] %*% + (t(eh$vectors[, keep, drop = FALSE]) / eh$values[keep]) + } + + ends <- cumsum(vapply(contrasts, function(x) nrow(x$L), integer(1L))) + cts <- lapply(seq_along(contrasts), function(i) { + cn <- contrasts[[i]] + idx <- (ends[i] - nrow(cn$L) + 1L):ends[i] + Jpsi <- if (robust) NULL else Jpsi_all[idx, , drop = FALSE] + .mixedCiContrast(cn$L, cn$n, beta, Vhat, gls$info, pieces, robust, + design, cn$counts, Jpsi, if (robust) NULL else Vpsi) + }) + out <- lapply(setNames(ci.method, ci.method), function(method) { + res <- lapply(seq_along(cts), function(i) { + .mixedCiInterval(cts[[i]], method, alpha, signed = i <= p) + }) + tab <- list(coefficients = do.call(rbind, res[seq_len(p)])) + rownames(tab$coefficients) <- names(beta) + if (!is.null(n_anova)) { + tab$anova <- do.call(rbind, res[-seq_len(p)]) + rownames(tab$anova) <- names(n_anova) + } + tab + }) + out$se <- vapply(cts, function(ct) if (ct$m1 == 1L) sqrt(ct$var_R) else NA_real_, numeric(1L)) + names(out$se) <- c(names(beta), names(n_anova)) + out +} diff --git a/R/resi_pe.R b/R/resi_pe.R index d2b9d05..1aeef47 100644 --- a/R/resi_pe.R +++ b/R/resi_pe.R @@ -779,142 +779,9 @@ resi_pe.gee <- function(model.full, data, unbiased = TRUE, ...){ return(output) } -#' @describeIn resi_pe RESI point estimation for lme object -#' @importFrom clubSandwich vcovCR -#' @export -resi_pe.lme <- function(model.full, anova = TRUE, vcovfunc = clubSandwich::vcovCR, - Anova.args = list(), vcov.args = list(), ...){ - x = as.matrix(summary(model.full)$tTable) - #sample size - N = summary(model.full)$dims$ngrps[1] - # robust se - if (length(vcov.args) == 0){ - vcov.args = c(formals(vcovfunc)[1], list(type = "CR3")) - } else{ - vcov.args = c(formals(vcovfunc)[1], vcov.args) - if (!("type" %in% names(vcov.args))){ - vcov.args = c(vcov.args, list(type = "CR3")) - }} - vcovfunc2 <- function(x) { - vcov.args[[1]] = x - do.call(vcovfunc, vcov.args)} - - robust.var = diag(vcovfunc2(model.full)) - robust.se = sqrt(robust.var) - coefficients.df = as.data.frame(cbind(x, 'Robust.SE' = robust.se, - 'Robust Wald' = (x[, 'Value']^2/robust.var), - RESI = RESI::chisq2S(x[, 'Value']^2/robust.var, 1, N))) - output = list(model.full = list(call = model.full$call, formula = formula(model.full)), - estimates = coefficients.df$RESI, coefficients = coefficients.df) - names(output$estimates) = rownames(coefficients.df) - - # Anova table (Chi sq statistics) - if (anova){ - suppressMessages(anova.tab <- do.call(car::Anova, c(list(mod = model.full, vcov. = vcovfunc2), Anova.args))) - anova.tab[,'RESI'] = chisq2S(anova.tab[,'Chisq'], anova.tab[,'Df'], N) - names.est = names(output$estimates) - output$estimates = c(output$estimates, anova.tab$RESI) - names.est = c(names.est, rownames(anova.tab)) - names(output$estimates) = names.est - output$anova = anova.tab - class(output$anova) = c("anova_resi", class(output$anova)) - } - if(identical(vcovfunc, stats::vcov)){ - output$naive.var = TRUE - } - else{ - output$naive.var = FALSE - } - class(output) = c("resi", "list") - return(output) -} - -#' @describeIn resi_pe RESI point estimation for lmerMod object -#' @export -resi_pe.lmerMod <- function(model.full, anova = TRUE, vcovfunc = clubSandwich::vcovCR, - Anova.args = list(), vcov.args = list(), unbiased = TRUE, ...){ - x = as.matrix(summary(model.full)$coefficients) - # sample size (number of clusters from primary grouping factor) - N = summary(model.full)$ngrps[[1]] - - # CS-RESI: extract primary cluster variable and compute per-observation weights - id_var <- names(lme4::ranef(model.full))[[1]] - data_mf_raw <- as.data.frame(model.frame(model.full)) - # model.frame(lmerMod) may only include transformed spline columns (e.g., - # "ns(Days, 3)") and omit the raw variable names needed to re-fit formulas. - # Reconstruct rows from the original data call when available. - data_mf <- tryCatch({ - data_arg <- model.full@call$data - if (is.null(data_arg)) stop("No data call stored") - data_full <- as.data.frame(eval(data_arg, envir = environment(formula(model.full)))) - used_rows <- rownames(data_mf_raw) - if (!is.null(used_rows) && length(used_rows) > 0 && all(used_rows %in% rownames(data_full))) { - data_full[used_rows, , drop = FALSE] - } else { - data_full - } - }, error = function(e) data_mf_raw) - n_i <- table(data_mf[[id_var]]) - data_mf$w_cs <- 1 / as.numeric(n_i[match(as.character(data_mf[[id_var]]), names(n_i))]) - # weighted independence lm (fixed effects only, random effects stripped) - fix_form <- reformulas::nobars(formula(model.full)) - mod_ind_lm <- lm(fix_form, data = data_mf, weights = w_cs) - # rescale residuals to undo the weight transformation (mirrors geeglm CS approach) - mod_ind_lm$residuals <- mod_ind_lm$residuals / sqrt(mod_ind_lm$weights) - # HC0 sandwich variance for CS model - cov_ind <- sandwich::vcovHC(mod_ind_lm, type = "HC0") - cs_coef_tab <- lmtest::coeftest(mod_ind_lm, vcov. = cov_ind) - - # robust se (L-RESI) - if (identical(vcovfunc, stats::vcov)) { - coefficients.tab = cbind(x, 'Wald' = x[, 't value']^2, - 'L-RESI' = RESI::chisq2S(x[, 't value']^2, 1, N), - 'CS-RESI' = z2S(cs_coef_tab[, 't value'], N, unbiased)) - output = list(estimates = coefficients.tab[,"L-RESI"], coefficients = coefficients.tab, naive.var = TRUE) - vcovfunc2 = vcovfunc - } else { - if (length(vcov.args) == 0){ - if (identical(vcovfunc, clubSandwich::vcovCR)){ - vcov.args = c(formals(vcovfunc)[1], list(type = "CR3")) - }} else{ - if (identical(vcovfunc, clubSandwich::vcovCR)){ - if (!("type" %in% names(vcov.args))){ - vcov.args = c(vcov.args, list(type = "CR3"))}} - vcov.args = c(formals(vcovfunc)[1], vcov.args)} - - vcovfunc2 <- function(x) { - vcov.args[[1]] = x - do.call(vcovfunc, vcov.args)} - robust_var = diag(vcovfunc2(model.full)) - robust_se = sqrt(robust_var) - coefficients.tab = cbind(x, 'Robust.SE' = robust_se, - 'Robust Wald' = (x[, 'Estimate']^2/robust_var), - 'L-RESI' = RESI::chisq2S(x[, 'Estimate']^2/robust_var, 1, N), - 'CS-RESI' = z2S(cs_coef_tab[, 't value'], N, unbiased)) - output = list(estimates = coefficients.tab[,"L-RESI"], coefficients = coefficients.tab, - naive.var = FALSE) - } - names(output$estimates) = rownames(coefficients.tab) - # Anova table (Chi sq statistics) - if (anova){ - suppressMessages(anova.tab <- do.call(car::Anova, - c(list(mod = model.full, vcov. = vcovfunc2), Anova.args))) - anova.tab[,'L-RESI'] = chisq2S(anova.tab[,'Chisq'], anova.tab[,'Df'], N) - # CS-RESI anova table: car::Anova on lm returns F-stats; F * Df = Wald Chisq - anova.tabcs <- suppressMessages(car::Anova(mod_ind_lm, vcov. = cov_ind)) - anova.tabcs <- anova.tabcs[!is.na(anova.tabcs[, "F"]), , drop = FALSE] - anova.tab[,'CS-RESI'] = chisq2S(anova.tabcs[,'F'] * anova.tabcs[,'Df'], anova.tabcs[,'Df'], N) - names.est = names(output$estimates) - output$estimates = c(output$estimates, anova.tab$`L-RESI`, anova.tab$`CS-RESI`) - names.est = c(names.est, rownames(anova.tab), rownames(anova.tab)) - names(output$estimates) = names.est - output$anova = anova.tab - class(output$anova) = c("anova_resi", class(output$anova)) - } - output$model.full = list(call = model.full@call, formula = formula(model.full)) - class(output) = c("resi", "list") - return(output) -} +## Mixed-model methods are defined in R/resi_pe_mixed.R. The preceding +## L-/CS-RESI methods have been archived under deprecated/ and are excluded +## from package builds. #' @describeIn resi_pe RESI point estimation for glmmTMB object - Gaussian only diff --git a/R/resi_pe_mixed.R b/R/resi_pe_mixed.R new file mode 100644 index 0000000..2cc33ed --- /dev/null +++ b/R/resi_pe_mixed.R @@ -0,0 +1,378 @@ +# [AI-generated: GitHub Copilot, 2026-09-29] +# [Prompt summary: mixed-model RESI with an explicit, term-specific normalizing n +# independent of the cluster used by the robust variance estimator.] + +.resiMixedModelDesign <- function(model.full, engine) { + if (engine == "lmerMod") { + X <- lme4::getME(model.full, "X") + groups <- as.list(lme4::getME(model.full, "flist")) + data <- tryCatch({ + data_arg <- model.full@call$data + if (is.null(data_arg)) stop("no stored data call") + d <- as.data.frame(eval(data_arg, envir = environment(formula(model.full)))) + mf <- model.frame(model.full) + used_rows <- rownames(mf) + if (!is.null(used_rows) && all(used_rows %in% rownames(d))) { + d[used_rows, , drop = FALSE] + } else { + as.data.frame(mf) + } + }, error = function(e) as.data.frame(model.frame(model.full))) + } else { + data <- as.data.frame(nlme::getData(model.full)) + fixed_formula <- formula(model.full) + X <- stats::model.matrix(stats::terms(fixed_formula), data = data) + dims <- summary(model.full)$dims + inner_to_outer <- rev(seq_len(dims$Q)) + groups <- lapply(inner_to_outer, function(k) nlme::getGroups(model.full, level = k)) + names(groups) <- names(dims$ngrps)[seq_len(dims$Q)] + } + if (nrow(X) != length(groups[[1]])) { + stop("The fixed-effect design and random-effect grouping rows do not align.") + } + list(X = X, assign = attr(X, "assign"), terms = attr(stats::terms( + if (engine == "lmerMod") reformulas::nobars(formula(model.full)) else formula(model.full) + ), "term.labels"), groups = groups, data = data) +} + +.resiMixedHasVariation <- function(x) { + if (is.null(dim(x))) x <- matrix(x, ncol = 1L) + if (nrow(x) < 2L) return(FALSE) + any(vapply(seq_len(ncol(x)), function(j) { + vals <- x[, j] + diff(range(vals, na.rm = TRUE)) > 1e-10 * max(1, max(abs(vals), na.rm = TRUE)) + }, logical(1L))) +} + +.resiMixedTermLevel <- function(term_matrix, groups, term_name) { + n_levels <- length(groups) + if (n_levels == 0L) stop("Mixed-model RESI requires at least one grouping factor.") + + for (k in seq_len(n_levels)) { + group <- droplevels(as.factor(groups[[k]])) + row_groups <- split(seq_along(group), group, drop = TRUE) + if (any(vapply(row_groups, function(idx) .resiMixedHasVariation(term_matrix[idx, , drop = FALSE]), logical(1L)))) { + return(list(variation_level = paste0("observation within ", names(groups)[[k]]), + n_level = names(groups)[[k]])) + } + + group_means <- do.call(rbind, lapply(row_groups, function(idx) { + colMeans(term_matrix[idx, , drop = FALSE]) + })) + if (k == n_levels) { + if (.resiMixedHasVariation(group_means)) { + return(list(variation_level = names(groups)[[k]], n_level = names(groups)[[k]])) + } + } else { + parent <- droplevels(as.factor(groups[[k + 1L]])) + parent_by_group <- vapply(row_groups, function(idx) { + values <- unique(as.character(parent[idx])) + if (length(values) != 1L) NA_character_ else values[[1L]] + }, character(1L)) + if (anyNA(parent_by_group)) { + stop("Cannot infer a term's variation level for crossed/non-nested grouping factors; supply `n` explicitly.") + } + sibling_groups <- split(seq_len(nrow(group_means)), parent_by_group, drop = TRUE) + if (any(vapply(sibling_groups, function(idx) { + .resiMixedHasVariation(group_means[idx, , drop = FALSE]) + }, logical(1L)))) { + return(list(variation_level = names(groups)[[k]], n_level = names(groups)[[k]])) + } + } + } + stop("Cannot infer a variation level for term '", term_name, + "' because it is constant across the observed design; supply `n` explicitly.") +} + +# Descriptive decomposition of a term's design-matrix variance across the +# nested grouping levels: grand mean -> outermost group means -> ... -> +# innermost group means -> observations. Sums of squares are taken over +# observations, so the components are orthogonal and add to the total; the +# observation-level remainder (1 - sum of returned proportions) is omitted. +# Multi-column terms pool sums of squares across columns. Returns NA when the +# term is constant or the grouping factors are not nested. +.resiMixedVarianceProportions <- function(term_matrix, groups) { + term_matrix <- as.matrix(term_matrix) + out <- setNames(rep(NA_real_, length(groups)), names(groups)) + centered <- sweep(term_matrix, 2L, colMeans(term_matrix)) + total <- sum(centered^2) + if (!is.finite(total) || total <= 1e-12 * max(1, nrow(term_matrix))) return(rev(out)) + group_means <- lapply(groups, function(g) { + g <- droplevels(as.factor(g)) + apply(term_matrix, 2L, function(x) ave(x, g)) + }) + for (k in seq_along(groups)) { + if (k < length(groups)) { + inner <- droplevels(as.factor(groups[[k]])) + outer <- droplevels(as.factor(groups[[k + 1L]])) + if (any(tapply(as.character(outer), inner, function(x) length(unique(x))) > 1L)) { + return(rev(out)) + } + parent <- group_means[[k + 1L]] + } else { + parent <- matrix(colMeans(term_matrix), nrow(term_matrix), ncol(term_matrix), byrow = TRUE) + } + out[[k]] <- sum((group_means[[k]] - parent)^2) / total + } + rev(out) +} + +.resiMixedScaleMap <- function(design, n = NULL, level = NULL) { + X <- as.matrix(design$X) + assign <- design$assign + term_labels <- design$terms + groups <- design$groups + group_counts <- vapply(groups, function(g) nlevels(droplevels(as.factor(g))), integer(1L)) + hierarchy_names <- rev(names(groups)) + hierarchy_counts <- rev(group_counts) + term_levels <- setNames(vector("list", length(term_labels)), term_labels) + + for (term_id in seq_along(term_labels)) { + cols <- which(assign == term_id) + term_levels[[term_labels[[term_id]]]] <- .resiMixedTermLevel( + X[, cols, drop = FALSE], groups, term_labels[[term_id]]) + } + term_levels <- c(list("(Intercept)" = list( + variation_level = "overall/intercept", + n_level = names(groups)[[1L]] + )), term_levels) + variation_levels <- vapply(term_levels, `[[`, character(1L), "variation_level") + n_levels <- vapply(term_levels, `[[`, character(1L), "n_level") + + if (is.null(level)) { + level <- 1L + message("No `level` supplied; using level 1 (", hierarchy_names[[1L]], + ") to normalize within-", hierarchy_names[[1L]], " terms.") + } + if (is.character(level) && length(level) == 1L) { + if (!level %in% hierarchy_names) { + stop("`level` must name a random-effect grouping factor or be a numeric hierarchy level.") + } + level_index <- match(level, hierarchy_names) + } else if (is.numeric(level) && length(level) == 1L && + is.finite(level) && level == as.integer(level) && + level >= 1L && level <= length(hierarchy_names)) { + level_index <- as.integer(level) + } else { + stop("`level` must be one numeric hierarchy level or a random-effect grouping name.") + } + selected_level <- hierarchy_names[[level_index]] + selected_n <- hierarchy_counts[[level_index]] + + if (!is.null(n)) { + if (length(n) != 1L || !is.numeric(n) || is.na(n) || + !is.finite(n) || n <= 0) { + stop("`n` must be one positive finite numeric normalizing count.") + } + selected_n <- n[[1L]] + selected_level <- "user-specified n" + # When n is user-supplied, use it for all terms (backward compatibility) + term_ns <- setNames(rep(selected_n, length(term_levels)), names(term_levels)) + n_levels[] <- selected_level + } else { + # Lyu & Welsh (2022): terms constant within the outermost cluster + # (intercept, cluster-level covariates) are normalized by the number of + # clusters g; all other terms by the number of units at `level`. + cluster_count <- hierarchy_counts[[1L]] + within_cluster_count <- hierarchy_counts[[level_index]] + top_cluster_name <- hierarchy_names[[1L]] + is_between_cluster <- variation_levels %in% c("overall/intercept", top_cluster_name) + + term_ns <- setNames( + ifelse( + is_between_cluster, + cluster_count, + within_cluster_count + ), + names(term_levels) + ) + n_levels <- ifelse(is_between_cluster, top_cluster_name, selected_level) + names(n_levels) <- names(term_levels) + } + + coefficient_terms <- character(ncol(X)) + for (j in seq_len(ncol(X))) { + term_id <- assign[[j]] + coefficient_terms[[j]] <- if (term_id == 0L) "(Intercept)" else term_labels[[term_id]] + } + names(coefficient_terms) <- colnames(X) + + prop_names <- paste("Var prop", rev(names(groups))) + coefficient_var_prop <- t(vapply(seq_len(ncol(X)), function(j) { + .resiMixedVarianceProportions(X[, j, drop = FALSE], groups) + }, numeric(length(groups)))) + if (length(groups) == 1L) coefficient_var_prop <- t(coefficient_var_prop) + dimnames(coefficient_var_prop) <- list(colnames(X), prop_names) + term_var_prop <- t(vapply(names(term_levels), function(term) { + cols <- if (term == "(Intercept)") which(assign == 0L) else which(assign == match(term, term_labels)) + .resiMixedVarianceProportions(X[, cols, drop = FALSE], groups) + }, numeric(length(groups)))) + if (length(groups) == 1L) term_var_prop <- t(term_var_prop) + dimnames(term_var_prop) <- list(names(term_levels), prop_names) + + list(variation_level = variation_levels, n_level = n_levels, + n = term_ns, coefficient_term = coefficient_terms, + coefficient_var_prop = coefficient_var_prop, term_var_prop = term_var_prop, + group_counts = group_counts, level = level_index, + level_name = selected_level) +} + +.resiMixedCluster <- function(cluster, design, model.full, engine) { + if (is.null(cluster)) return(NULL) + if (is.character(cluster) && length(cluster) == 1L) { + if (cluster %in% names(design$groups)) return(design$groups[[cluster]]) + if (cluster %in% names(design$data)) return(design$data[[cluster]]) + stop("`cluster` must name a model grouping factor or a column in the fitted data.") + } + if (length(cluster) != nrow(design$X)) { + stop("A supplied `cluster` vector must have one value per model observation.") + } + cluster +} + +.resiMixedVcov <- function(model.full, vcovfunc, vcov.args, cluster) { + if (!is.null(cluster) && "cluster" %in% names(vcov.args)) { + stop("Specify the robust-variance cluster either with `cluster` or `vcov.args$cluster`, not both.") + } + if (identical(vcovfunc, clubSandwich::vcovCR) && !("type" %in% names(vcov.args))) { + vcov.args$type <- "CR3" + } + if (!is.null(cluster)) vcov.args$cluster <- cluster + fast_cr2 <- identical(vcovfunc, clubSandwich::vcovCR) && inherits(model.full, "lmerMod") && + identical(vcov.args$type, "CR2") && all(names(vcov.args) %in% c("type", "cluster")) && + !is.null(vcov.args$cluster) && all(stats::weights(model.full) == 1) + function(object) { + if (fast_cr2) { + out <- tryCatch(.mixedCiCR2(object, vcov.args$cluster), error = function(e) NULL) + if (!is.null(out)) return(out) + } + do.call(vcovfunc, c(list(object), vcov.args)) + } +} + +.resi_pe_mixed <- function(model.full, engine, anova, vcovfunc, Anova.args, + vcov.args, unbiased, n, level, cluster, include_level) { + design <- .resiMixedModelDesign(model.full, engine) + scale_map <- .resiMixedScaleMap(design, n, level) + cluster_vec <- .resiMixedCluster(cluster, design, model.full, engine) + vcovfun <- .resiMixedVcov(model.full, vcovfunc, vcov.args, cluster_vec) + coefficient_summary <- if (engine == "lmerMod") { + as.matrix(summary(model.full)$coefficients) + } else { + as.matrix(summary(model.full)$tTable) + } + estimate_name <- if (engine == "lmerMod") "Estimate" else "Value" + estimate <- coefficient_summary[, estimate_name] + coefficient_terms <- scale_map$coefficient_term[rownames(coefficient_summary)] + coefficient_n <- unname(scale_map$n[coefficient_terms]) + + naive <- identical(vcovfunc, stats::vcov) + if (naive) { + covariance <- stats::vcov(model.full) + se <- sqrt(diag(as.matrix(covariance)))[rownames(coefficient_summary)] + } else { + covariance <- vcovfun(model.full) + se <- sqrt(diag(covariance))[rownames(coefficient_summary)] + } + statistic <- estimate / se + coefficient_table <- as.data.frame(coefficient_summary) + if (!naive) coefficient_table$Robust.SE <- unname(se) + coefficient_table$Wald <- statistic^2 + coefficient_table$RESI <- z2S(statistic, coefficient_n, unbiased) + coefficient_table$Term <- unname(coefficient_terms) + coefficient_table$n <- coefficient_n + if (include_level) { + coefficient_table$`Variation level` <- unname(scale_map$variation_level[coefficient_terms]) + coefficient_table$`n level` <- unname(scale_map$n_level[coefficient_terms]) + coefficient_table <- cbind(coefficient_table, as.data.frame( + scale_map$coefficient_var_prop[rownames(coefficient_summary), , drop = FALSE], + check.names = FALSE)) + } + + output <- list(estimates = setNames(coefficient_table$RESI, rownames(coefficient_table)), + coefficients = coefficient_table, naive.var = naive) + + if (anova) { + if (naive) { + anova_table <- suppressMessages(do.call(car::Anova, + c(list(mod = model.full), Anova.args))) + } else { + anova_table <- suppressMessages(do.call(car::Anova, + c(list(mod = model.full, vcov. = vcovfun), Anova.args))) + } + anova_terms <- rownames(anova_table) + missing_terms <- setdiff(anova_terms, names(scale_map$n)) + if (length(missing_terms)) { + stop("Could not map ANOVA terms to fixed-effect terms: ", + paste(missing_terms, collapse = ", ")) + } + anova_n <- unname(scale_map$n[anova_terms]) + anova_table$RESI <- chisq2S(anova_table$Chisq, anova_table$Df, anova_n) + anova_table$n <- anova_n + if (include_level) { + anova_table$`Variation level` <- unname(scale_map$variation_level[anova_terms]) + anova_table$`n level` <- unname(scale_map$n_level[anova_terms]) + for (prop_name in colnames(scale_map$term_var_prop)) { + anova_table[[prop_name]] <- unname(scale_map$term_var_prop[anova_terms, prop_name]) + } + } + output$estimates <- c(output$estimates, setNames(anova_table$RESI, anova_terms)) + output$anova <- anova_table + class(output$anova) <- c("anova_resi", class(output$anova)) + } + output$model.full <- list(call = if (engine == "lmerMod") model.full@call else model.full$call, + formula = formula(model.full)) + class(output) <- c("resi", "list") + output +} + +#' @describeIn resi_pe Mixed-model RESI point estimation +#' @param n Optional positive scalar normalizing count applied to every +#' coefficient and ANOVA term. If `NULL` (default), the count is +#' term-specific (Lyu & Welsh, 2022): terms constant within the outermost +#' grouping factor (including the intercept) use the number of outermost +#' groups, and all other terms use the number of groups at `level`. +#' @param level Random-effect hierarchy level or grouping-factor name whose +#' group count normalizes terms that vary within the outermost grouping +#' factor. Numeric levels are ordered from outermost to innermost grouping +#' (for `egsingle`, school is level 1 and student is level 2). If omitted, +#' level 1 is used and a message names the grouping factor. +#' @param cluster Optional grouping-factor name or observation-length vector +#' specifying the cluster used only by `vcovfunc`. `NULL` leaves the +#' variance function's default unchanged. For `clubSandwich::vcovCR`, this +#' is commonly the outermost grouping factor; it need not equal the level +#' used to infer `n`. +#' @param include_level Logical; add `Variation level` and `n level` columns +#' to coefficient and ANOVA tables (default `TRUE`). `Variation level` +#' reports the lowest observed design level at which a term changes; +#' `n level` reports the grouping factor whose count is the term's `n`. These can differ (e.g., `year` varies by occasion within a +#' student, while its default `n` counts students). Explicit `n` overrides +#' retain the design-derived variation label and mark `n level` as +#' user-specified. Also adds one `Var prop ` column per grouping +#' factor (outermost first): the share of the fixed-effect design column's +#' (coefficients) or term's (ANOVA; pooled across its columns) observation- +#' level sum of squares lying between units of that grouping factor within +#' the next-outer one. The remainder, `1 - sum`, is the share varying within +#' the innermost group. Values are `NA` for the intercept and for +#' non-nested grouping factors. +#' @importFrom clubSandwich vcovCR +#' @export +resi_pe.lmerMod <- function(model.full, anova = TRUE, + vcovfunc = clubSandwich::vcovCR, + Anova.args = list(), vcov.args = list(), + unbiased = TRUE, n = NULL, level = NULL, cluster = NULL, + include_level = TRUE, ...) { + .resi_pe_mixed(model.full, "lmerMod", anova, vcovfunc, Anova.args, + vcov.args, unbiased, n, level, cluster, include_level) +} + +#' @describeIn resi_pe Mixed-model RESI point estimation +#' @export +resi_pe.lme <- function(model.full, anova = TRUE, + vcovfunc = clubSandwich::vcovCR, + Anova.args = list(), vcov.args = list(), + unbiased = TRUE, n = NULL, level = NULL, cluster = NULL, + include_level = TRUE, ...) { + .resi_pe_mixed(model.full, "lme", anova, vcovfunc, Anova.args, + vcov.args, unbiased, n, level, cluster, include_level) +} diff --git a/man/designAveragedSe.Rd b/man/designAveragedSe.Rd new file mode 100644 index 0000000..461b039 --- /dev/null +++ b/man/designAveragedSe.Rd @@ -0,0 +1,36 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/mixed_simulations.R +\name{designAveragedSe} +\alias{designAveragedSe} +\title{Design-averaged per-unit SE for the hybrid plasmode} +\usage{ +designAveragedSe( + fit, + g, + m, + n_rep = 2000L, + school = "schoolid", + child = "childid:schoolid" +) +} +\arguments{ +\item{fit}{A `lmerMod` fit of `y ~ X + (1 | school/child)`.} + +\item{g}{Number of schools.} + +\item{m}{Average number of students per school.} + +\item{n_rep}{Number of resampled school sets.} + +\item{school, child}{Names of the school and child grouping factors in +`lme4::getME(fit, "flist")`.} +} +\description{ +sqrt(n_k E_X[V(X)]_kk) at g schools and average m students per school, +averaging the conditional covariance V(X) = I(X)^{-1} over `n_rep` +resampled sets of g school profiles. Because beta-hat is conditionally +unbiased this is the finite-(g, m) reference for the Monte Carlo SD of +beta-hat; it exceeds `expectedDesignResi()$se_unit` since +E[I^{-1}] >= E[I]^{-1}. +} +\keyword{internal} diff --git a/man/expectedDesignResi.Rd b/man/expectedDesignResi.Rd new file mode 100644 index 0000000..3420f05 --- /dev/null +++ b/man/expectedDesignResi.Rd @@ -0,0 +1,27 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/mixed_simulations.R +\name{expectedDesignResi} +\alias{expectedDesignResi} +\title{Fixed-m RESI under the expected hybrid plasmode design} +\usage{ +expectedDesignResi(fit, m, school = "schoolid", child = "childid:schoolid") +} +\arguments{ +\item{fit}{A `lmerMod` fit of `y ~ X + (1 | school/child)`.} + +\item{m}{Average number of students per school.} + +\item{school, child}{Names of the school and child grouping factors in +`lme4::getME(fit, "flist")`.} +} +\value{ +As [lyuLimitResi()] plus `se_unit`, sqrt(n_k Var_kk). +} +\description{ +Exact RESI and per-unit SE when each school profile is represented in +proportion to its sampling probability with average `m` students per +school (the number of schools g cancels). Converges to [lyuLimitResi()] as +m -> Inf; equals `resi_pe(level = 2)` on the observed design at +m = mean school size. +} +\keyword{internal} diff --git a/man/hybridPlasmodeSim.Rd b/man/hybridPlasmodeSim.Rd new file mode 100644 index 0000000..48375ea --- /dev/null +++ b/man/hybridPlasmodeSim.Rd @@ -0,0 +1,60 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/mixed_simulations.R +\name{hybridPlasmodeSim} +\alias{hybridPlasmodeSim} +\title{Hybrid plasmode calibration simulation for three-level mixed-model RESI} +\usage{ +hybridPlasmodeSim( + formula, + data, + school = "schoolid", + child = "childid", + n_schools = c(15, 30, 60, 100), + n_per_site = c(25, 100, 200), + nsim = 1000L, + mc.cores = 1L, + seed = 2026, + control = lme4::lmerControl(optimizer = "bobyqa", optCtrl = list(maxfun = 2e+05)), + rep_fun = NULL, + keep_reps = !is.null(rep_fun) +) +} +\arguments{ +\item{formula}{Model formula of the form `y ~ X + (1 | school/child)`.} + +\item{data}{Data frame containing the variables in `formula`.} + +\item{school, child}{Names of the school and child id columns of `data`.} + +\item{n_schools, n_per_site}{Vectors crossed to form the simulation grid.} + +\item{nsim}{Number of replicates per grid cell.} + +\item{mc.cores}{Number of cores for [parallel::mclapply()] over replicates.} + +\item{seed}{Seed (with the "L'Ecuyer-CMRG" generator) for reproducibility.} + +\item{control}{`lme4::lmerControl()` used for all fits.} + +\item{rep_fun}{Optional `function(fit, design)` evaluated on each replicate +fit; its return value is stored as `extra` in the replicate output.} + +\item{keep_reps}{Logical; return the per-replicate output.} +} +\value{ +A list with `summary` (parameter-level calibration per cell), + `resi_summary` (RESI calibration per cell and term), `truth_fit`, + `truth_resi`, and optionally `reps` (per cell). +} +\description{ +Fits `formula` (ML) to `data` and treats the fitted fixed effects and +variance components as the data-generating truth. Each replicate +(i) resamples `n_schools` school covariate profiles with replacement and, +within each, students with replacement in proportion to the observed school +size so that the average is `n_per_site`; (ii) draws school and student +random effects with replacement from the BLUP pools, each centred and +rescaled to the fitted variance component, plus Gaussian residuals; +(iii) refits by REML and computes `resi_pe(level = 2)` with the model-based +covariance. RESI and per-unit SE targets are the Lyu-Welsh g, m -> Inf +limit at the full-data ML estimates ([lyuLimitResi()]). +} diff --git a/man/lyuLimitResi.Rd b/man/lyuLimitResi.Rd new file mode 100644 index 0000000..12bfef5 --- /dev/null +++ b/man/lyuLimitResi.Rd @@ -0,0 +1,27 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/mixed_simulations.R +\name{lyuLimitResi} +\alias{lyuLimitResi} +\title{Lyu-Welsh limiting RESI for a three-level random-intercept lmer fit} +\usage{ +lyuLimitResi(fit, school = "schoolid", child = "childid:schoolid") +} +\arguments{ +\item{fit}{A `lmerMod` fit of `y ~ X + (1 | school/child)`.} + +\item{school, child}{Names of the school and child grouping factors in +`lme4::getME(fit, "flist")`.} +} +\value{ +List with `coefficients` and `anova` RESI tables, the logical + `between` indicator per column, and the per-unit limiting covariance `V`. +} +\description{ +Evaluates the g, m -> Inf limit (Lyu & Welsh, 2022) of the per-unit +covariance of the fixed effects and the corresponding RESI at the fitted +parameters. Between-school columns: n_g Var(beta_b) -> tau2_school C^{-1}, +C = g^{-1} sum_s x_s x_s'. Within-school columns: the school intercept acts +as a fixed effect, so I_w / N = N^{-1} sum_s (A_s - b_s b_s' / c_s). The +between and within blocks are asymptotically independent. +} +\keyword{internal} diff --git a/man/resi.Rd b/man/resi.Rd index 62e05c3..c64dad0 100644 --- a/man/resi.Rd +++ b/man/resi.Rd @@ -279,6 +279,8 @@ resi(model.full, ...) anova = TRUE, vcovfunc = clubSandwich::vcovCR, vcov.args = list(), + ci.method = c("normal", "qf", "cf", "none"), + ci.design = TRUE, ... ) @@ -336,6 +338,9 @@ resi(model.full, ...) One of `"boot"` (bootstrap), `"qf"` (quadratic-form inversion, default for lm and glm), `"normal"` (normal approximation), or `"cf"` (Cornish-Fisher inversion). See `resi_pe_asymptotic` for details on the asymptotic methods.} + +\item{ci.design}{Logical; for `lmerMod` CIs, include the variability of +the cluster-level design.} } \value{ Returns a list that includes function arguments, RESI point estimates, @@ -416,7 +421,16 @@ and then try rerunning \code{resi}. \item \code{resi(lme)}: RESI point and interval estimation for LME (nlme) models -\item \code{resi(lmerMod)}: RESI point and interval estimation for lmerMod models +\item \code{resi(lmerMod)}: RESI point and asymptotic interval estimation for lmerMod +models whose random effects are nested in an outermost cluster. CIs use +cluster-level influence functions (`ci.method` one of `"normal"`, `"qf"`, +`"cf"`; coefficients get the signed normal CI for `"qf"`). Use +`vcovfunc = stats::vcov` for model-based or `clubSandwich::vcovCR` (e.g. +`vcov.args = list(type = "CR2")`) for cluster-robust intervals. +`ci.design = TRUE` (default) treats the cluster covariate profiles as +sampled; `FALSE` gives intervals conditional on the observed design. +`ci.method = "none"` returns point estimates only. ANOVA CIs are for the +joint Wald test of each term's columns (Type II without interactions). \item \code{resi(glmmTMB)}: RESI point and interval estimation for glmmTMB models - Gaussian only diff --git a/man/resi_pe.Rd b/man/resi_pe.Rd index 50f855f..daaab40 100644 --- a/man/resi_pe.Rd +++ b/man/resi_pe.Rd @@ -1,5 +1,5 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/resi_pe.R +% Please edit documentation in R/resi_pe.R, R/resi_pe_mixed.R \name{resi_pe} \alias{resi_pe} \alias{resi_pe.default} @@ -15,10 +15,10 @@ \alias{resi_pe.geeglm} \alias{resi_pe.glmgee} \alias{resi_pe.gee} -\alias{resi_pe.lme} -\alias{resi_pe.lmerMod} \alias{resi_pe.glmmTMB} \alias{resi_pe.emmGrid} +\alias{resi_pe.lmerMod} +\alias{resi_pe.lme} \title{Robust Effect Size Index (RESI) Point Estimation} \usage{ resi_pe(...) @@ -184,7 +184,7 @@ resi_pe(...) \method{resi_pe}{gee}(model.full, data, unbiased = TRUE, ...) -\method{resi_pe}{lme}( +\method{resi_pe}{glmmTMB}( model.full, anova = TRUE, vcovfunc = clubSandwich::vcovCR, @@ -193,6 +193,8 @@ resi_pe(...) ... ) +\method{resi_pe}{emmGrid}(object, model, N = NULL, unbiased = TRUE, ...) + \method{resi_pe}{lmerMod}( model.full, anova = TRUE, @@ -200,19 +202,26 @@ resi_pe(...) Anova.args = list(), vcov.args = list(), unbiased = TRUE, + n = NULL, + level = NULL, + cluster = NULL, + include_level = TRUE, ... ) -\method{resi_pe}{glmmTMB}( +\method{resi_pe}{lme}( model.full, anova = TRUE, vcovfunc = clubSandwich::vcovCR, Anova.args = list(), vcov.args = list(), + unbiased = TRUE, + n = NULL, + level = NULL, + cluster = NULL, + include_level = TRUE, ... ) - -\method{resi_pe}{emmGrid}(object, model, N = NULL, unbiased = TRUE, ...) } \arguments{ \item{...}{Ignored.} @@ -244,6 +253,38 @@ resi_pe(...) \item{model}{model used to generate emmeans} \item{N}{sample size} + +\item{n}{Optional positive scalar normalizing count applied to every +coefficient and ANOVA term. If `NULL` (default), the count is +term-specific (Lyu & Welsh, 2022): terms constant within the outermost +grouping factor (including the intercept) use the number of outermost +groups, and all other terms use the number of groups at `level`.} + +\item{level}{Random-effect hierarchy level or grouping-factor name whose +group count normalizes terms that vary within the outermost grouping +factor. Numeric levels are ordered from outermost to innermost grouping +(for `egsingle`, school is level 1 and student is level 2). If omitted, +level 1 is used and a message names the grouping factor.} + +\item{cluster}{Optional grouping-factor name or observation-length vector +specifying the cluster used only by `vcovfunc`. `NULL` leaves the +variance function's default unchanged. For `clubSandwich::vcovCR`, this +is commonly the outermost grouping factor; it need not equal the level +used to infer `n`.} + +\item{include_level}{Logical; add `Variation level` and `n level` columns +to coefficient and ANOVA tables (default `TRUE`). `Variation level` +reports the lowest observed design level at which a term changes; +`n level` reports the grouping factor whose count is the term's `n`. These can differ (e.g., `year` varies by occasion within a +student, while its default `n` counts students). Explicit `n` overrides +retain the design-derived variation label and mark `n level` as +user-specified. Also adds one `Var prop ` column per grouping +factor (outermost first): the share of the fixed-effect design column's +(coefficients) or term's (ANOVA; pooled across its columns) observation- +level sum of squares lying between units of that grouping factor within +the next-outer one. The remainder, `1 - sum`, is the share varying within +the innermost group. Values are `NA` for the intercept and for +non-nested grouping factors.} } \value{ Returns a list containing RESI point estimates @@ -313,14 +354,14 @@ using a model where each measurement is its own cluster. \item \code{resi_pe(gee)}: RESI point estimation for gee object -\item \code{resi_pe(lme)}: RESI point estimation for lme object - -\item \code{resi_pe(lmerMod)}: RESI point estimation for lmerMod object - \item \code{resi_pe(glmmTMB)}: RESI point estimation for glmmTMB object - Gaussian only \item \code{resi_pe(emmGrid)}: RESI point estimation for emmeans object +\item \code{resi_pe(lmerMod)}: Mixed-model RESI point estimation + +\item \code{resi_pe(lme)}: Mixed-model RESI point estimation + }} \examples{ # This function produces point estimates for the RESI. The resi function will diff --git a/tests/testthat/test-resi-mixed-ci.R b/tests/testthat/test-resi-mixed-ci.R new file mode 100644 index 0000000..1cd3902 --- /dev/null +++ b/tests/testthat/test-resi-mixed-ci.R @@ -0,0 +1,90 @@ +egsingle_ci_data <- function() { + egsingle <- local({ + env <- new.env() + utils::data("egsingle", package = "mlmRev", envir = env) + env$egsingle + }) + egsingle$size_100 <- egsingle$size / 100 + egsingle$lowinc_10 <- egsingle$lowinc / 10 + egsingle +} +form_ci <- math ~ year + female + black + hispanic + size_100 + lowinc_10 + + (1 | schoolid/childid) + +test_that("fast CR2 equals clubSandwich CR2 and GLS pieces reproduce lme4", { + skip_if_not_installed("lme4") + skip_if_not_installed("mlmRev") + skip_if_not_installed("clubSandwich") + eg <- egsingle_ci_data() + sub <- droplevels(subset(eg, schoolid %in% levels(schoolid)[1:12])) + fit <- lme4::lmer(form_ci, data = sub, REML = TRUE) + expect_equal(unname(.mixedCiCR2(fit, "schoolid")), + unname(as.matrix(clubSandwich::vcovCR(fit, cluster = sub$schoolid, type = "CR2"))), + tolerance = 1e-8) + + base <- .mixedCiBase(fit, "schoolid") + gls <- .mixedCiGls(base, base$theta, base$sigma) + expect_equal(unname(.mixedCiDeviance(base, c(base$theta, base$sigma))), unname(lme4::REMLcrit(fit))) + expect_equal(unname(solve(gls$info)), unname(as.matrix(stats::vcov(fit))), tolerance = 1e-6) + pieces <- .mixedCiClusterPieces(base, gls) + expect_equal(unname(matrix(colSums(pieces$I_s), ncol(base$X))), unname(gls$info)) + expect_equal(unname(colSums(pieces$U_s)), rep(0, ncol(base$X)), tolerance = 1e-6) +}) + +test_that("design-variance linearization matches resampling of school profiles", { + skip_if_not_installed("lme4") + skip_if_not_installed("mlmRev") + eg <- egsingle_ci_data() + fit <- lme4::lmer(form_ci, data = eg, REML = FALSE) + base <- .mixedCiBase(fit, "schoolid") + gls <- .mixedCiGls(base, base$theta, base$sigma) + pieces <- .mixedCiClusterPieces(base, gls) + p <- ncol(base$X) + counts <- tapply(lme4::getME(fit, "flist")[["childid:schoolid"]], base$cluster, + function(x) length(unique(x))) + L <- matrix(colnames(base$X) == "year", 1L) + Vhat <- solve(gls$info) + design_sd <- function(n_k, cnt) { + with_design <- .mixedCiContrast(L, n_k, gls$beta, Vhat, gls$info, pieces, FALSE, TRUE, cnt) + without <- .mixedCiContrast(L, n_k, gls$beta, Vhat, gls$info, pieces, FALSE, FALSE, cnt) + sqrt(drop(with_design$var_R - without$var_R)) + } + set.seed(1) + g <- nrow(pieces$I_s) + k <- which(L[1, ]) + boot <- replicate(2000, { + s <- sample.int(g, g, replace = TRUE) + Istar <- matrix(colSums(pieces$I_s[s, , drop = FALSE]), p) + gls$beta[k] / sqrt(sum(counts[s]) * solve(Istar)[k, k]) + }) + expect_equal(design_sd(sum(counts), counts), stats::sd(boot), tolerance = 0.1) + # Omitting the unit-count perturbation grossly overstates the design SD. + expect_gt(design_sd(sum(counts), NULL), 2 * stats::sd(boot)) +}) + +test_that("resi() on lmerMod returns ordered RESI intervals for each method", { + skip_if_not_installed("lme4") + skip_if_not_installed("mlmRev") + skip_if_not_installed("clubSandwich") + skip_if_not_installed("numDeriv") + eg <- egsingle_ci_data() + sub <- droplevels(subset(eg, schoolid %in% levels(schoolid)[1:20])) + fit <- lme4::lmer(form_ci, data = sub, REML = TRUE) + check <- function(out) { + for (tab in list(out$coefficients, out$anova)) { + expect_true(all(c("2.5%", "97.5%") %in% names(tab))) + expect_true(all(tab[["2.5%"]] <= tab$RESI & tab$RESI <= tab[["97.5%"]])) + } + } + for (method in c("normal", "qf", "cf")) { + check(resi(fit, vcovfunc = stats::vcov, ci.method = method, level = 2)) + } + robust <- resi(fit, vcov.args = list(type = "CR2"), cluster = "schoolid", + ci.method = "normal", level = 2) + check(robust) + expect_equal(robust$coefficients$Robust.SE, + unname(sqrt(diag(.mixedCiCR2(fit, "schoolid"))))) + expect_warning(none <- resi(fit, vcovfunc = stats::vcov, ci.method = "none", level = 2), + "point estimates only") + expect_false("2.5%" %in% names(none$coefficients)) +}) diff --git a/tests/testthat/test-resi-mixed-scale.R b/tests/testthat/test-resi-mixed-scale.R new file mode 100644 index 0000000..5912858 --- /dev/null +++ b/tests/testthat/test-resi-mixed-scale.R @@ -0,0 +1,75 @@ +test_that("mixed-model RESI normalizes between-school terms by g and within-school terms by N", { + skip_if_not_installed("lme4") + skip_if_not_installed("mlmRev") + + egsingle <- local({ + env <- new.env() + utils::data("egsingle", package = "mlmRev", envir = env) + env$egsingle + }) + egsingle$schoolid <- factor(egsingle$schoolid) + egsingle$childid <- factor(egsingle$childid) + egsingle$size_100 <- egsingle$size / 100 + egsingle$lowinc_10 <- egsingle$lowinc / 10 + + fit <- lme4::lmer( + math ~ year + female + black + hispanic + size_100 + lowinc_10 + + (1 | schoolid/childid), + data = egsingle, + REML = FALSE + ) + pe <- resi_pe(fit, anova = TRUE, vcovfunc = stats::vcov, level = 2) + + expect_true(all(c("RESI", "Term", "n", "Variation level", "n level") %in% names(pe$coefficients))) + expect_false(any(c("L-RESI", "CS-RESI") %in% names(pe$coefficients))) + between <- c("(Intercept)", "size_100", "lowinc_10") + expected_n <- ifelse(rownames(pe$coefficients) %in% between, 60, 1721) + expect_equal(pe$coefficients$n, expected_n) + expect_equal(pe$coefficients$`n level`, + ifelse(rownames(pe$coefficients) %in% between, "schoolid", "childid:schoolid")) + expect_equal(pe$coefficients["year", "Variation level"], "observation within childid:schoolid") + expect_equal(pe$coefficients["lowinc_10", "Variation level"], "schoolid") + expect_true(all(c("RESI", "n", "Variation level", "n level") %in% names(pe$anova))) + expect_equal(pe$anova$n, ifelse(rownames(pe$anova) %in% between, 60, 1721)) + + prop_cols <- c("Var prop schoolid", "Var prop childid:schoolid") + expect_true(all(prop_cols %in% names(pe$coefficients))) + expect_true(all(prop_cols %in% names(pe$anova))) + expect_true(all(is.na(pe$coefficients["(Intercept)", prop_cols]))) + expect_equal(unname(unlist(pe$coefficients["lowinc_10", prop_cols])), c(1, 0)) + year_props <- unname(unlist(pe$coefficients["year", prop_cols])) + expect_true(all(year_props > 0) && sum(year_props) < 1) + expect_equal(pe$anova["black", "Var prop schoolid"], + pe$coefficients["black1", "Var prop schoolid"]) + + pe_default <- expect_message( + resi_pe(fit, anova = FALSE, vcovfunc = stats::vcov), + "level 1") + expect_true(all(pe_default$coefficients$n == 60)) + expect_true(all(pe_default$coefficients$`n level` == "schoolid")) + pe_global <- suppressMessages(resi_pe(fit, anova = FALSE, n = 100, + vcovfunc = stats::vcov)) + expect_true(all(pe_global$coefficients$n == 100)) + + pe_no_level <- suppressWarnings(resi_pe(fit, anova = FALSE, include_level = FALSE)) + expect_false("Variation level" %in% names(pe_no_level$coefficients)) + expect_false("n level" %in% names(pe_no_level$coefficients)) + expect_true("n" %in% names(pe_no_level$coefficients)) +}) + +test_that("nlme mixed-model RESI uses the same normalizer API", { + skip_if_not_installed("nlme") + + fit <- nlme::lme(distance ~ age + Sex, data = nlme::Orthodont, + random = ~1 | Subject, method = "ML") + pe <- suppressMessages(resi_pe(fit, anova = TRUE, vcovfunc = stats::vcov)) + + expect_true(all(c("RESI", "n", "Variation level", "n level") %in% names(pe$coefficients))) + expect_false(any(c("L-RESI", "CS-RESI") %in% names(pe$coefficients))) + expect_true(all(pe$coefficients$n == 27)) + expect_equal(pe$coefficients["age", "Variation level"], "observation within Subject") + expect_true(all(pe$coefficients$`n level` == "Subject")) + expect_true(all(c("RESI", "n", "Variation level") %in% names(pe$anova))) + expect_equal(pe$coefficients["age", "Var prop Subject"], 0) + expect_equal(pe$anova["Sex", "Var prop Subject"], 1) +}) diff --git a/tests/testthat/test-resi.R b/tests/testthat/test-resi.R index 14b2f74..a713ed3 100644 --- a/tests/testthat/test-resi.R +++ b/tests/testthat/test-resi.R @@ -277,10 +277,10 @@ test_that("resi produces the correct estimates", { # # geeglmRESI = resi_pe(ggmod) # } expect_equal(unname(suppressWarnings(resi(mod.lme, nboot = 10)$coefficients[,'RESI'])), - c(3.659090, 1.739166, 0.512371), tolerance = 1e-07) + c(3.664148, 1.749782, -0.547322), tolerance = 1e-06) if(requireNamespace("lme4")){ - expect_equal(unname(suppressWarnings(resi(mod.lmerMod, nboot = 10)$coefficients[,'L-RESI'])), - c(8.434942, 1.533073), tolerance = 1e-07)} + expect_equal(unname(suppressWarnings(resi(mod.lmerMod, nboot = 10)$coefficients[,'RESI'])), + c(8.438235, 1.551086), tolerance = 1e-06)} if(requireNamespace("glmmTMB")){ expect_equal(unname(suppressWarnings(resi(model_glmmTMB, nboot = 10)$coefficients[,'RESI'])), c( 6.22903, 3.06823), tolerance = 1e-05) @@ -353,33 +353,11 @@ test_that("bootstrap succeeds for models with transformed responses", { }) if(requireNamespace("lme4")){ -test_that("lmerMod: L-RESI and CS-RESI point estimates are correct", { - pe = suppressWarnings(resi_pe(mod.lmerMod)) - expect_equal(unname(pe$coefficients[,'L-RESI']), - c(8.434942, 1.533073), tolerance = 1e-07) - expect_equal(unname(pe$coefficients[,'CS-RESI']), - c(3.6680844, 0.6185898), tolerance = 1e-06) - expect_equal(unname(pe$anova[,'L-RESI']), 1.533073, tolerance = 1e-06) - expect_equal(unname(pe$anova[,'CS-RESI']), 0.5719247, tolerance = 1e-06) -}) - -if(requireNamespace("geepack")){ -test_that("geeglm (exchangeable, positive rho) L-RESI matches lmerMod (CR0) L-RESI", { - sdata = lme4::sleepstudy - sdata$subjid = as.integer(sdata$Subject) - mod_lmer_ri = lme4::lmer(Reaction ~ Days + (1 | Subject), sdata) - mod_gee_exch = geepack::geeglm(Reaction ~ Days, data = sdata, id = subjid, - family = gaussian, corstr = "exchangeable") - pe_lmer = suppressWarnings(resi_pe(mod_lmer_ri, vcov.args = list(type = "CR0"))) - pe_gee = resi_pe(mod_gee_exch) - # for positive exchangeable correlation (alpha ~ 0.58), GEE and CR0 sandwich - # give the same L-RESI up to finite-sample differences - expect_equal(unname(pe_lmer$coefficients[,'L-RESI']), - unname(pe_gee$coefficients[,'L-RESI']), tolerance = 0.05) - # CS-RESI is identical: both compute the same weighted independence lm + HC0 - expect_equal(unname(pe_lmer$coefficients[,'CS-RESI']), - unname(pe_gee$coefficients[,'CS-RESI']), tolerance = 1e-07) -})}} +test_that("lmerMod mixed-model RESI uses the new normalizer output", { + pe <- suppressWarnings(resi_pe(mod.lmerMod, anova = FALSE)) + expect_true(all(c("RESI", "n", "Variation level") %in% names(pe$coefficients))) + expect_false(any(c("L-RESI", "CS-RESI") %in% names(pe$coefficients))) +})} if(requireNamespace("gee") & requireNamespace("geepack")){ test_that("vcov methods same for gee and geeglm",{ @@ -497,7 +475,7 @@ test_that("tibbles work", { # expect_equal(unname(resi(mod.glmgee.tib, nboot = 10)$coefficients[,'L-RESI']), c(-0.02585617, -0.48811210, 0.01414410, 0.56177861, -0.29398258), tolerance = 1e-07) # } if(requireNamespace("lme4")){ - expect_equal(unname(suppressWarnings(resi(mod.lmerMod.tib, nboot = 10))$coefficients[,'L-RESI']),c(8.434942, 1.533073), tolerance = 1e-07) + expect_equal(unname(suppressWarnings(resi(mod.lmerMod.tib, nboot = 10))$coefficients[,'RESI']),c(8.438235, 1.551086), tolerance = 1e-06) } })} diff --git a/tests/testthat/test-resi_asymptotic.R b/tests/testthat/test-resi_asymptotic.R index ad0b967..f157313 100644 --- a/tests/testthat/test-resi_asymptotic.R +++ b/tests/testthat/test-resi_asymptotic.R @@ -147,6 +147,12 @@ test_that("Normal and QF anova CIs are close for large n (lm)", { label = "normal vs QF CI widths agree within 30%") }) +test_that("QF CI is correct when the noncentrality exceeds the pnorm-branch threshold", { + # n * S^2 / Sigma_R > 1e4 uses the (Z + sqrt(ncp))^2 identity. + ct <- list(m1 = 1L, n = 20000, R_beta = 3.33, Stilde = 3.33, Sigma_R = matrix(20)) + expect_equal(.resi_ci_qf(ct), .resi_ci_normal_unsigned(ct), tolerance = 1e-3) +}) + # =========================================================================== # 7. CI bounds agree on coefficients: normal and QF both use signed normal From 7ef14930a917aac3017a5d26afb82da1e98a211a Mon Sep 17 00:00:00 2001 From: simonvandekar Date: Mon, 16 Nov 2026 07:20:35 -0600 Subject: [PATCH 2/6] Fast CR2: handle singular fits (theta = 0); test random slopes and singular fits against clubSandwich Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- R/resi_mixed_ci.R | 13 +++++++++---- tests/testthat/test-resi-mixed-ci.R | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/R/resi_mixed_ci.R b/R/resi_mixed_ci.R index ec62206..322897d 100644 --- a/R/resi_mixed_ci.R +++ b/R/resi_mixed_ci.R @@ -85,10 +85,15 @@ Zs <- as.matrix(Zs[, Matrix::colSums(Zs != 0) > 0, drop = FALSE]) # Thin left singular vectors of Zs via the small q_s x q_s eigenproblem # (LAPACK dgesdd occasionally fails to converge on these matrices). - ez <- eigen(crossprod(Zs), symmetric = TRUE) - keep <- ez$values > max(ez$values) * 1e-12 - sv <- list(d = sqrt(ez$values[keep])) - sv$u <- Zs %*% (ez$vectors[, keep, drop = FALSE] %*% diag(1 / sv$d, length(sv$d))) + # (Zs has no columns when theta = 0, i.e. a singular fit.) + if (ncol(Zs) == 0L) { + sv <- list(d = numeric(0), u = matrix(0, length(idx), 0L)) + } else { + ez <- eigen(crossprod(Zs), symmetric = TRUE) + keep <- ez$values > max(ez$values) * 1e-12 + sv <- list(d = sqrt(ez$values[keep])) + sv$u <- Zs %*% (ez$vectors[, keep, drop = FALSE] %*% diag(1 / sv$d, length(sv$d))) + } vpow <- function(B, a) { base$sigma^(2 * a) * (B + sv$u %*% (((1 + sv$d^2)^a - 1) * crossprod(sv$u, B))) } diff --git a/tests/testthat/test-resi-mixed-ci.R b/tests/testthat/test-resi-mixed-ci.R index 1cd3902..6c016b0 100644 --- a/tests/testthat/test-resi-mixed-ci.R +++ b/tests/testthat/test-resi-mixed-ci.R @@ -31,6 +31,24 @@ test_that("fast CR2 equals clubSandwich CR2 and GLS pieces reproduce lme4", { expect_equal(unname(colSums(pieces$U_s)), rep(0, ncol(base$X)), tolerance = 1e-6) }) +test_that("fast CR2 matches clubSandwich for random slopes and singular fits", { + skip_if_not_installed("lme4") + skip_if_not_installed("clubSandwich") + ss <- lme4::sleepstudy + slope <- lme4::lmer(Reaction ~ Days + (Days | Subject), data = ss) + expect_equal(unname(.mixedCiCR2(slope, "Subject")), + unname(as.matrix(clubSandwich::vcovCR(slope, cluster = ss$Subject, type = "CR2"))), + tolerance = 1e-8) + set.seed(1) + d <- data.frame(g = factor(rep(1:30, each = 4)), x = rnorm(120)) + d$y <- d$x + rnorm(120) + sing <- suppressMessages(lme4::lmer(y ~ x + (1 | g), data = d)) + skip_if_not(lme4::isSingular(sing)) + expect_equal(unname(.mixedCiCR2(sing, "g")), + unname(as.matrix(clubSandwich::vcovCR(sing, cluster = d$g, type = "CR2"))), + tolerance = 1e-8) +}) + test_that("design-variance linearization matches resampling of school profiles", { skip_if_not_installed("lme4") skip_if_not_installed("mlmRev") From 87aa33e8b95f675ab59c685a7e12dbf809fae16e Mon Sep 17 00:00:00 2001 From: simonvandekar Date: Mon, 16 Nov 2026 07:32:42 -0600 Subject: [PATCH 3/6] Mixed-model RESI CIs for nlme::lme fits - .mixedCiBaseLme(): lme4-style representation (X, y, Zt, Lambdat, Lind, theta, sigma) of an lme fit, reproducing lme's beta, vcov and logLik; theta respects pdDiag/pdIdent constraints. Fits with varFunc/corStruct or other pdMat classes fall back to point estimates with a warning. - resi.lme gains ci.method/ci.design; resi.lme and resi.lmerMod share .resiMixedWithCi(). ANOVA heading preserved. - Fast exact CR2 also used for supported lme fits. - Tests: lme vs lmer intervals agree; lme CR2 equals clubSandwich. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- R/resi.R | 51 +++++++++---- R/resi_mixed_ci.R | 107 ++++++++++++++++++++++++---- R/resi_pe_mixed.R | 6 +- man/resi.Rd | 13 +++- tests/testthat/test-resi-mixed-ci.R | 38 ++++++++++ 5 files changed, 182 insertions(+), 33 deletions(-) diff --git a/R/resi.R b/R/resi.R index ef7e521..8eb9d79 100644 --- a/R/resi.R +++ b/R/resi.R @@ -737,19 +737,32 @@ resi.gee = function(model.full, data, nboot = 1000, alpha = 0.05, return(output) } -#' @describeIn resi RESI point and interval estimation for LME (nlme) models +#' @describeIn resi RESI point and asymptotic interval estimation for LME +#' (nlme) models whose random effects are nested in an outermost cluster; +#' identical method and arguments to the `lmerMod` method. Supported fits +#' have independent homoscedastic within-group errors (no `weights` or +#' `correlation`) and pdSymm/pdLogChol/pdDiag/pdIdent random-effect +#' covariances; other fits return point estimates only, with a warning. #' @importFrom nlme getGroups #' @export -resi.lme = function(model.full, alpha = 0.05, nboot = 1000, anova = TRUE, vcovfunc = clubSandwich::vcovCR, - vcov.args = list(), ...){ - warning("\nConfidence Interval procedure not developed for lme, returning point estimates only") - output = list(alpha = alpha, nboot = 0) - # RESI point estimates - output = c(output, resi_pe(model.full = model.full, vcovfunc = vcovfunc, vcov.args = vcov.args, - anova = anova, ...)) - output$boot.method = "nonparam" - class(output) = "resi" - return(output) +resi.lme = function(model.full, alpha = 0.05, nboot = 1000, anova = TRUE, + vcovfunc = clubSandwich::vcovCR, vcov.args = list(), + ci.method = c("normal", "qf", "cf", "none"), + ci.design = TRUE, ...){ + ci.method <- match.arg(ci.method) + why <- .mixedCiLmeUnsupported(model.full) + if (ci.method != "none" && !is.null(why)) { + warning("\nConfidence intervals not available for this lme fit (", why, + "); returning point estimates only") + output = list(alpha = alpha, nboot = 0) + output = c(output, resi_pe(model.full = model.full, vcovfunc = vcovfunc, vcov.args = vcov.args, + anova = anova, ...)) + output$boot.method = "nonparam" + class(output) = "resi" + return(output) + } + .resiMixedWithCi(model.full, "lme", alpha, anova, vcovfunc, vcov.args, + ci.method, ci.design, ...) } #' @describeIn resi RESI point and asymptotic interval estimation for lmerMod @@ -762,21 +775,27 @@ resi.lme = function(model.full, alpha = 0.05, nboot = 1000, anova = TRUE, vcovfu #' sampled; `FALSE` gives intervals conditional on the observed design. #' `ci.method = "none"` returns point estimates only. ANOVA CIs are for the #' joint Wald test of each term's columns (Type II without interactions). -#' @param ci.design Logical; for `lmerMod` CIs, include the variability of -#' the cluster-level design. +#' @param ci.design Logical; for `lmerMod` and `lme` CIs, include the +#' variability of the cluster-level design. #' @export resi.lmerMod = function(model.full, alpha = 0.05, nboot = 1000, anova = TRUE, vcovfunc = clubSandwich::vcovCR, vcov.args = list(), ci.method = c("normal", "qf", "cf", "none"), ci.design = TRUE, ...){ ci.method <- match.arg(ci.method) + .resiMixedWithCi(model.full, "lmerMod", alpha, anova, vcovfunc, vcov.args, + ci.method, ci.design, ...) +} + +.resiMixedWithCi <- function(model.full, engine, alpha, anova, vcovfunc, vcov.args, + ci.method, ci.design, ...) { dots <- list(...) robust <- !identical(vcovfunc, stats::vcov) pe_vcovfunc <- vcovfunc if (ci.method != "none" && robust) { - design <- .resiMixedModelDesign(model.full, "lmerMod") + design <- .resiMixedModelDesign(model.full, engine) Vhat <- .resiMixedVcov(model.full, vcovfunc, vcov.args, - .resiMixedCluster(dots$cluster, design, model.full, "lmerMod"))(model.full) + .resiMixedCluster(dots$cluster, design, model.full, engine))(model.full) pe_vcovfunc <- function(object, ...) Vhat } output = list(alpha = alpha, nboot = 0) @@ -800,12 +819,14 @@ resi.lmerMod = function(model.full, alpha = 0.05, nboot = 1000, anova = TRUE, output$coefficients[-seq_len(pos)]) if (anova) { anova_class <- class(output$anova) + anova_heading <- attr(output$anova, "heading") pos <- match("RESI", names(output$anova)) anova_df <- as.data.frame(output$anova) output$anova <- cbind(anova_df[seq_len(pos)], setNames(as.data.frame(cis$anova), ci_cols), anova_df[-seq_len(pos)]) class(output$anova) <- anova_class + attr(output$anova, "heading") <- anova_heading } output$ci.method <- ci.method } else { diff --git a/R/resi_mixed_ci.R b/R/resi_mixed_ci.R index 322897d..aa5272f 100644 --- a/R/resi_mixed_ci.R +++ b/R/resi_mixed_ci.R @@ -1,4 +1,4 @@ -# Asymptotic RESI confidence intervals for lmerMod fits with random effects +# Asymptotic RESI confidence intervals for lmerMod and nlme::lme fits with random effects # nested in an outermost cluster (derivation: AIgams notes/resi_mixed_ci.qmd). # # Var(R_hat) is estimated from school-level (outermost-cluster) influence @@ -41,19 +41,100 @@ } .mixedCiBase <- function(fit, cluster) { - fl <- lme4::getME(fit, "flist") + base <- if (inherits(fit, "lme")) .mixedCiBaseLme(fit) else { + list(X = lme4::getME(fit, "X"), y = lme4::getME(fit, "y"), Zt = lme4::getME(fit, "Zt"), + Lambdat = lme4::getME(fit, "Lambdat"), Lind = lme4::getME(fit, "Lind"), + theta = lme4::getME(fit, "theta"), sigma = stats::sigma(fit), + REML = lme4::isREML(fit), beta = lme4::fixef(fit), + flist = as.list(lme4::getME(fit, "flist"))) + } + fl <- base$flist if (is.null(cluster)) cluster <- names(fl)[which.min(vapply(fl, nlevels, integer(1L)))] cl <- if (length(cluster) == 1L && cluster %in% names(fl)) fl[[cluster]] else cluster cl <- droplevels(as.factor(cl)) - Zt <- lme4::getME(fit, "Zt") - zt <- methods::as(Zt, "TsparseMatrix") + zt <- methods::as(base$Zt, "TsparseMatrix") if (any(tapply(as.integer(cl)[zt@j + 1L], zt@i, function(x) length(unique(x))) > 1L)) { stop("Mixed-model RESI CIs require every random effect to be nested within `cluster`.") } - list(X = lme4::getME(fit, "X"), y = lme4::getME(fit, "y"), Zt = Zt, - Lambdat = lme4::getME(fit, "Lambdat"), Lind = lme4::getME(fit, "Lind"), - theta = lme4::getME(fit, "theta"), sigma = stats::sigma(fit), - REML = lme4::isREML(fit), cluster = cl) + base$cluster <- cl + base +} + +# Reasons an nlme::lme fit is outside the supported class (homoscedastic, +# independent within-group errors; unstructured, diagonal or identity +# random-effect covariances), or NULL when supported. +.mixedCiLmeUnsupported <- function(fit) { + ms <- fit$modelStruct + if (!is.null(ms$varStruct)) return("`weights` (variance functions) are not supported") + if (!is.null(ms$corStruct)) return("`correlation` structures are not supported") + ok <- vapply(ms$reStruct, function(pd) inherits(pd, c("pdLogChol", "pdSymm", "pdDiag", "pdIdent")), + logical(1L)) + if (!all(ok)) return("random-effect covariance classes other than pdSymm/pdLogChol/pdDiag/pdIdent are not supported") + NULL +} + +# The lme4 representation of an lme fit: V = sigma^2 (I + Z Lambda Lambda' Z'), +# with Lambda block diagonal in the per-level relative Cholesky factors and +# theta their free entries (lower triangle for unstructured, diagonal for +# pdDiag, one shared value for pdIdent), so the deviance Hessian respects the +# model's covariance constraints. +.mixedCiBaseLme <- function(fit) { + why <- .mixedCiLmeUnsupported(fit) + if (!is.null(why)) stop("Mixed-model RESI CIs for lme: ", why, ".") + design <- .resiMixedModelDesign(fit, "lme") + data <- design$data + X <- stats::model.matrix(stats::terms(stats::formula(fit)), data = data, + contrasts.arg = fit$contrasts) + beta <- nlme::fixef(fit) + if (!identical(colnames(X), names(beta))) stop("Could not rebuild the lme fixed-effect design.") + y <- nlme::getResponse(fit) + re <- fit$modelStruct$reStruct + n <- nrow(X) + zi <- zj <- integer(0); zx <- numeric(0) + li <- lj <- lt <- integer(0) + theta <- numeric(0) + offset <- 0L + # reStruct is stored innermost first; getGroups(level = k) and fit$groups + # run outermost first, so levels are matched by name. + for (k in seq_along(re)) { + pd <- re[[k]] + Zk <- stats::model.matrix(stats::formula(pd), data = data) + q <- ncol(Zk) + grp <- droplevels(as.factor(nlme::getGroups(fit, level = match(names(re)[k], names(fit$groups))))) + J <- nlevels(grp) + gi <- as.integer(grp) + for (c in seq_len(q)) { + zi <- c(zi, seq_len(n)); zj <- c(zj, offset + (gi - 1L) * q + c); zx <- c(zx, Zk[, c]) + } + D <- as.matrix(pd) + if (inherits(pd, c("pdDiag", "pdIdent"))) { + Lk <- diag(sqrt(diag(D)), q) + pos <- cbind(seq_len(q), seq_len(q)) + tid <- if (inherits(pd, "pdIdent")) rep(1L, q) else seq_len(q) + th <- if (inherits(pd, "pdIdent")) Lk[1, 1] else diag(Lk) + } else { + Lk <- t(chol(D)) + pos <- which(lower.tri(Lk, diag = TRUE), arr.ind = TRUE) + pos <- pos[order(pos[, 2], pos[, 1]), , drop = FALSE] + tid <- seq_len(nrow(pos)) + th <- Lk[pos] + } + # Lambdat = t(Lambda): entry (r, c) of the lower factor sits at (c, r). + for (j in seq_len(J)) { + li <- c(li, offset + (j - 1L) * q + pos[, 2]) + lj <- c(lj, offset + (j - 1L) * q + pos[, 1]) + lt <- c(lt, length(theta) + tid) + } + theta <- c(theta, th) + offset <- offset + J * q + } + Zt <- Matrix::t(Matrix::sparseMatrix(i = zi, j = zj, x = zx, dims = c(n, offset))) + Lambdat <- Matrix::sparseMatrix(i = li, j = lj, x = seq_along(li), dims = c(offset, offset)) + Lind <- lt[Lambdat@x] + Lambdat@x <- theta[Lind] + list(X = X, y = as.numeric(y), Zt = Zt, Lambdat = Lambdat, Lind = Lind, + theta = theta, sigma = fit$sigma, REML = identical(fit$method, "REML"), + beta = beta, flist = rev(design$groups)) } # Per-cluster information contributions I_s (g x p^2) and scores U_s (g x p). @@ -65,7 +146,7 @@ } # CR2 cluster-robust covariance (Pustejovsky & Tipton, 2018) with working -# covariance V, matching clubSandwich::vcovCR(fit, type = "CR2") for lmerMod +# covariance V, matching clubSandwich::vcovCR(fit, type = "CR2") for lmerMod and lme # fits with random effects nested in `cluster`, without its n_s x n_s matrix # roots. clubSandwich adjusts W_s e_s by A_s = V_s^{1/2} G_s^{-1/2} V_s^{1/2}, # G_s = V_s^{1/2} (V_s - X_s M X_s') V_s^{1/2}. With V_s = sigma^2 (I + Z_s Z_s') @@ -193,8 +274,8 @@ #' Mixed-model RESI confidence intervals (internal) #' #' Computes asymptotic CIs for the coefficient (signed) and ANOVA (unsigned) -#' RESI of an `lmerMod` fit, for terms normalized by `n_coef`/`n_anova`. -#' @param fit `lmerMod` fit whose random effects are nested in `cluster`. +#' RESI of an `lmerMod` or `lme` fit, for terms normalized by `n_coef`/`n_anova`. +#' @param fit `lmerMod` or `lme` fit whose random effects are nested in `cluster`. #' @param Vhat Covariance of the fixed effects used for the point estimates. #' @param robust Logical; `Vhat` is a cluster-robust sandwich. #' @param n_coef,n_anova Named term-specific normalizing counts. @@ -218,12 +299,12 @@ base <- .mixedCiBase(fit, cluster) gls <- .mixedCiGls(base, base$theta, base$sigma) pieces <- .mixedCiClusterPieces(base, gls) - beta <- lme4::fixef(fit) + beta <- base$beta Vhat <- as.matrix(Vhat)[names(beta), names(beta)] p <- length(beta) assign <- attr(base$X, "assign") terms <- .mixedFixedTermLabels(fit) - fl <- lme4::getME(fit, "flist") + fl <- base$flist unit_counts <- function(n_k, lev) { if (n_k == nlevels(base$cluster)) return(NULL) if (is.null(lev) || !(lev %in% names(fl))) { diff --git a/R/resi_pe_mixed.R b/R/resi_pe_mixed.R index 2cc33ed..2adae3a 100644 --- a/R/resi_pe_mixed.R +++ b/R/resi_pe_mixed.R @@ -238,9 +238,11 @@ vcov.args$type <- "CR3" } if (!is.null(cluster)) vcov.args$cluster <- cluster - fast_cr2 <- identical(vcovfunc, clubSandwich::vcovCR) && inherits(model.full, "lmerMod") && + fast_cr2 <- identical(vcovfunc, clubSandwich::vcovCR) && identical(vcov.args$type, "CR2") && all(names(vcov.args) %in% c("type", "cluster")) && - !is.null(vcov.args$cluster) && all(stats::weights(model.full) == 1) + !is.null(vcov.args$cluster) && + ((inherits(model.full, "lmerMod") && all(stats::weights(model.full) == 1)) || + (inherits(model.full, "lme") && is.null(.mixedCiLmeUnsupported(model.full)))) function(object) { if (fast_cr2) { out <- tryCatch(.mixedCiCR2(object, vcov.args$cluster), error = function(e) NULL) diff --git a/man/resi.Rd b/man/resi.Rd index c64dad0..9e4dcbf 100644 --- a/man/resi.Rd +++ b/man/resi.Rd @@ -269,6 +269,8 @@ resi(model.full, ...) anova = TRUE, vcovfunc = clubSandwich::vcovCR, vcov.args = list(), + ci.method = c("normal", "qf", "cf", "none"), + ci.design = TRUE, ... ) @@ -339,8 +341,8 @@ One of `"boot"` (bootstrap), `"qf"` (quadratic-form inversion, default for lm an `"normal"` (normal approximation), or `"cf"` (Cornish-Fisher inversion). See `resi_pe_asymptotic` for details on the asymptotic methods.} -\item{ci.design}{Logical; for `lmerMod` CIs, include the variability of -the cluster-level design.} +\item{ci.design}{Logical; for `lmerMod` and `lme` CIs, include the +variability of the cluster-level design.} } \value{ Returns a list that includes function arguments, RESI point estimates, @@ -419,7 +421,12 @@ and then try rerunning \code{resi}. \item \code{resi(gee)}: RESI point and interval estimation for GEE models -\item \code{resi(lme)}: RESI point and interval estimation for LME (nlme) models +\item \code{resi(lme)}: RESI point and asymptotic interval estimation for LME +(nlme) models whose random effects are nested in an outermost cluster; +identical method and arguments to the `lmerMod` method. Supported fits +have independent homoscedastic within-group errors (no `weights` or +`correlation`) and pdSymm/pdLogChol/pdDiag/pdIdent random-effect +covariances; other fits return point estimates only, with a warning. \item \code{resi(lmerMod)}: RESI point and asymptotic interval estimation for lmerMod models whose random effects are nested in an outermost cluster. CIs use diff --git a/tests/testthat/test-resi-mixed-ci.R b/tests/testthat/test-resi-mixed-ci.R index 6c016b0..91645f4 100644 --- a/tests/testthat/test-resi-mixed-ci.R +++ b/tests/testthat/test-resi-mixed-ci.R @@ -106,3 +106,41 @@ test_that("resi() on lmerMod returns ordered RESI intervals for each method", { "point estimates only") expect_false("2.5%" %in% names(none$coefficients)) }) + +test_that("resi() on lme reproduces the lmerMod intervals and falls back when unsupported", { + skip_if_not_installed("lme4") + skip_if_not_installed("mlmRev") + skip_if_not_installed("clubSandwich") + skip_if_not_installed("numDeriv") + eg <- egsingle_ci_data() + sub <- droplevels(subset(eg, schoolid %in% levels(schoolid)[1:20])) + sub$math[c(5, 50, 500)] <- NA + fit_lmer <- lme4::lmer(form_ci, data = sub, REML = TRUE) + fit_lme <- nlme::lme(math ~ year + female + black + hispanic + size_100 + lowinc_10, + random = ~ 1 | schoolid/childid, data = sub, na.action = na.omit) + base <- .mixedCiBase(fit_lme, "schoolid") + gls <- .mixedCiGls(base, base$theta, base$sigma) + expect_equal(unname(gls$beta), unname(nlme::fixef(fit_lme)), tolerance = 1e-8) + expect_equal(.mixedCiDeviance(base, c(base$theta, base$sigma)), + -2 * as.numeric(stats::logLik(fit_lme)), tolerance = 1e-8) + cols <- c("RESI", "2.5%", "97.5%") + for (args in list(list(vcovfunc = stats::vcov), + list(vcov.args = list(type = "CR2"), cluster = "schoolid"))) { + a <- suppressMessages(do.call(resi, c(list(fit_lme, ci.method = "qf", level = 2), args))) + b <- suppressMessages(do.call(resi, c(list(fit_lmer, ci.method = "qf", level = 2), args))) + expect_equal(unname(as.matrix(a$coefficients[cols])), unname(as.matrix(b$coefficients[cols])), + tolerance = 1e-4) + expect_equal(unname(as.matrix(as.data.frame(a$anova)[cols])), + unname(as.matrix(as.data.frame(b$anova)[cols])), tolerance = 1e-4) + } + slope <- nlme::lme(Reaction ~ Days, random = ~ Days | Subject, data = lme4::sleepstudy) + expect_equal(unname(.mixedCiCR2(slope, "Subject")), + unname(as.matrix(clubSandwich::vcovCR(slope, cluster = lme4::sleepstudy$Subject, + type = "CR2"))), + tolerance = 1e-8) + hetero <- nlme::lme(Reaction ~ Days, random = ~ 1 | Subject, data = lme4::sleepstudy, + weights = nlme::varIdent(form = ~ 1 | Days > 4)) + expect_warning(out <- suppressMessages(resi(hetero, vcovfunc = stats::vcov)), + "not available for this lme fit") + expect_false("2.5%" %in% names(out$coefficients)) +}) From 9d76b5fd1ef1687300feefac0a9afaec46b542b9 Mon Sep 17 00:00:00 2001 From: simonvandekar Date: Mon, 16 Nov 2026 07:42:59 -0600 Subject: [PATCH 4/6] QF 1-df interval: always use the exact (Z + sqrt(ncp))^2 identity; plasmode skips rank-deficient replicates - .resi_ci_qf (m1 = 1): P(chi2_1(ncp) >= q) = pnorm(sqrt(ncp) - sqrt(q)) + pnorm(-sqrt(ncp) - sqrt(q)) for all q and ncp. pnchisq warned about lost precision for moderately large arguments and returned 0 in far tails. - hybridPlasmodeSim: replicates whose resampled design loses a factor level (rank-deficient refit) are counted as failed fits. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- R/mixed_simulations.R | 3 +++ R/resi_asymptotic.R | 19 ++++++++----------- tests/testthat/test-resi_asymptotic.R | 11 +++++++++-- 3 files changed, 20 insertions(+), 13 deletions(-) diff --git a/R/mixed_simulations.R b/R/mixed_simulations.R index 701b41f..9df23e6 100644 --- a/R/mixed_simulations.R +++ b/R/mixed_simulations.R @@ -318,6 +318,9 @@ hybridPlasmodeSim <- function(formula, data, school = "schoolid", child = "child lme4::lmer(formula, data = design, REML = TRUE, control = control))), error = function(e) NULL) if (is.null(fit)) return(NULL) + # A resampled design can miss a rare factor level; such replicates are + # counted as failed fits rather than estimating a different model. + if (length(lme4::fixef(fit)) != length(beta)) return(NULL) point <- resi_pe(fit, anova = TRUE, vcovfunc = stats::vcov, level = 2) list(params = .mixedSimParams(fit), fe_se = setNames(sqrt(diag(as.matrix(stats::vcov(fit)))), fe_names), diff --git a/R/resi_asymptotic.R b/R/resi_asymptotic.R index c77b82f..2dd6ebb 100644 --- a/R/resi_asymptotic.R +++ b/R/resi_asymptotic.R @@ -584,20 +584,17 @@ # For m1>1: use imhof if (m1 == 1L) { q <- T2_obs / lambda[1] - # For large q or ncp, use the exact identity chi^2(1,lambda) = (Z + sqrt(lambda))^2: - # P(chi^2(1,lambda) >= q) = pnorm(sqrt(lambda) - sqrt(q)) + pnorm(-sqrt(lambda) - sqrt(q)) - # This avoids pnchisq convergence failures (which arise when q and ncp are both large, - # e.g. ~1e12, as happens in ill-conditioned GLMs at small n). The formula is - # algebraically exact and pnorm is numerically stable at arbitrarily large arguments. + # Exact identity chi^2(1,lambda) = (Z + sqrt(lambda))^2: + # P(chi^2(1,lambda) >= q) = pnorm(sqrt(lambda) - sqrt(q)) + pnorm(-sqrt(lambda) - sqrt(q)). + # Used for all q and lambda: pnchisq loses precision (or returns 0 in the + # tails) once q and lambda reach the hundreds, whereas pnorm is accurate + # at any argument. prob_fn <- function(S_b) { nc <- nc_fun(S_b) if (!is.finite(nc)) return(1.0) - if (q > 1e4 || nc > 1e4) { - sq <- sqrt(max(q, 0)) - snc <- sqrt(max(nc, 0)) - return(pnorm(snc - sq) + pnorm(-snc - sq)) - } - pchisq(q, df = 1, ncp = nc, lower.tail = FALSE) + sq <- sqrt(max(q, 0)) + snc <- sqrt(max(nc, 0)) + pnorm(snc - sq) + pnorm(-snc - sq) } } else { prob_fn <- function(S_b) { diff --git a/tests/testthat/test-resi_asymptotic.R b/tests/testthat/test-resi_asymptotic.R index f157313..bca769b 100644 --- a/tests/testthat/test-resi_asymptotic.R +++ b/tests/testthat/test-resi_asymptotic.R @@ -147,10 +147,17 @@ test_that("Normal and QF anova CIs are close for large n (lm)", { label = "normal vs QF CI widths agree within 30%") }) -test_that("QF CI is correct when the noncentrality exceeds the pnorm-branch threshold", { - # n * S^2 / Sigma_R > 1e4 uses the (Z + sqrt(ncp))^2 identity. +test_that("QF CI for one df is correct for large and moderate noncentrality", { + # Large n * S^2 / Sigma_R: the QF interval approaches the normal interval. ct <- list(m1 = 1L, n = 20000, R_beta = 3.33, Stilde = 3.33, Sigma_R = matrix(20)) expect_equal(.resi_ci_qf(ct), .resi_ci_normal_unsigned(ct), tolerance = 1e-3) + # Moderate: the bounds invert the noncentral chi-square(1) test exactly. + ct <- list(m1 = 1L, n = 50, R_beta = 0.6, Stilde = 0.6, Sigma_R = matrix(1.3)) + ci <- .resi_ci_qf(ct) + q <- ct$n * ct$Stilde^2 / 1.3 + tail_at <- function(s) pchisq(q, 1, ncp = ct$n * s^2 / 1.3, lower.tail = FALSE) + expect_equal(tail_at(ci[[1]]), 0.025, tolerance = 1e-3) + expect_equal(tail_at(ci[[2]]), 0.975, tolerance = 1e-3) }) From 1e8da5e00f0b7932637586f1a81aeb72da1ffbc1 Mon Sep 17 00:00:00 2001 From: simonvandekar Date: Tue, 17 Nov 2026 15:24:47 -0600 Subject: [PATCH 5/6] Mixed CIs: t(g-1) reference for CR2 by default; child-level random slopes - .resi_ci_mixed(ref.df = NULL): g - 1 for cluster-robust (CR2) intervals, normal otherwise. Normal/QF/CF/signed-CF support a finite reference df; QF/CF use t noise with an unscaled signal, integrated over W ~ chi^2_d with 20-node generalized Gauss-Laguerre quadrature. - resi_pe for mixed models: random-slope terms use the number of units at the slope level as n. - hybridPlasmodeSim/lyuLimitResi support child-level random effects. - Tests for the finite-df intervals and CR2 t widths. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- R/mixed_simulations.R | 113 ++++++++++++------ R/resi.R | 4 +- R/resi_asymptotic.R | 153 ++++++++++++++++++++++--- R/resi_mixed_ci.R | 18 ++- R/resi_pe_mixed.R | 46 +++++++- man/designAveragedSe.Rd | 4 +- man/expectedDesignResi.Rd | 4 +- man/hybridPlasmodeSim.Rd | 4 +- man/lyuLimitResi.Rd | 6 +- man/resi.Rd | 4 +- man/resi_pe.Rd | 6 +- tests/testthat/test-resi-mixed-ci.R | 9 ++ tests/testthat/test-resi-mixed-scale.R | 26 +++++ tests/testthat/test-resi_asymptotic.R | 17 +++ 14 files changed, 349 insertions(+), 65 deletions(-) diff --git a/R/mixed_simulations.R b/R/mixed_simulations.R index 9df23e6..d915ac2 100644 --- a/R/mixed_simulations.R +++ b/R/mixed_simulations.R @@ -1,6 +1,12 @@ +# [AI-generated: GitHub Copilot, 2026-11-15] +# [Prompt summary: Lyu-Welsh limiting RESI targets and hybrid plasmode +# calibration of mixed-model RESI on mlmRev::egsingle.] + # Mixed-model RESI calibration: Lyu & Welsh (2022) limiting targets and the -# hybrid plasmode simulation for a three-level random-intercept lmer model -# `y ~ X + (1 | school/child)` (developed on mlmRev::egsingle). +# hybrid plasmode simulation for a three-level lmer model with a school random +# intercept and child-level random effects, e.g. `y ~ X + (1 | school/child)` +# or `y ~ X + (1 | school) + (year | child:school)` (developed on +# mlmRev::egsingle). # # Design convention (matches the plasmode): schools are drawn uniformly from # the observed school profiles and students within a school in proportion to @@ -13,12 +19,25 @@ # n_k = N students for within-school terms, matching resi_pe(level = 2). .mixedVarComps <- function(fit, school, child) { - vc <- as.data.frame(lme4::VarCorr(fit)) - list(tau2_school = vc$vcov[vc$grp == school & is.na(vc$var2)], - tau2_child = vc$vcov[vc$grp == child & is.na(vc$var2)], + vc <- lme4::VarCorr(fit) + if (length(vc[[school]]) != 1L) { + stop("Only a random intercept is supported at the school level (", school, ").") + } + G_child <- as.matrix(vc[[child]]) + attributes(G_child) <- list(dim = dim(G_child), dimnames = dimnames(G_child)) + list(tau2_school = as.numeric(vc[[school]]), + G_child = G_child, tau2_child = G_child[1L, 1L], sigma2 = stats::sigma(fit)^2) } +# Child-level random-effects design Z (observations x q) of `fit`. +.mixedChildZ <- function(fit, child) { + mm <- lme4::getME(fit, "mmList") + hit <- which(sub(".*\\|\\s*", "", names(mm)) == child) + if (length(hit) != 1L) stop("Expected one random-effects term for ", child, ".") + as.matrix(mm[[hit]]) +} + .mixedBetweenColumns <- function(X, school_id) { vapply(seq_len(ncol(X)), function(j) { all(tapply(X[, j], school_id, function(x) diff(range(x)) < 1e-10)) @@ -30,27 +49,36 @@ } # Per-school sufficient statistics of the GLS information for a three-level -# random-intercept model with the school effect integrated out: +# model with a school random intercept integrated out: # A_s = sum_j X_j' W_j^{-1} X_j, b_s = sum_j X_j' W_j^{-1} 1, -# c_s = sum_j 1' W_j^{-1} 1, W_j = sigma2 I + tau2_child 11', -# so school s contributes A_s - b_s b_s' / (1 / tau2_school + c_s). -lyuSchoolStats <- function(X, school_id, child_id, tau2_child, sigma2) { +# c_s = sum_j 1' W_j^{-1} 1, W_j = sigma2 I + Z_j G Z_j', +# so school s contributes A_s - b_s b_s' / (1 / tau2_school + c_s). Z holds the +# child-level random-effects columns (default: a random intercept, G = tau2) +# and W_j^{-1} = (I - Z_j M_j Z_j') / sigma2 with M_j = (sigma2 I + G Z_j'Z_j)^{-1} G. +lyuSchoolStats <- function(X, school_id, child_id, G_child, sigma2, + Z = matrix(1, nrow(X), 1L)) { + G_child <- as.matrix(G_child) child_id <- droplevels(as.factor(child_id)) school_of_child <- tapply(as.character(school_id), child_id, `[`, 1L) - T_j <- as.numeric(table(child_id)) - k_j <- tau2_child / (sigma2 + T_j * tau2_child) - sx <- rowsum(X, child_id) rows <- split(seq_len(nrow(X)), child_id) + q <- ncol(Z) + per_child <- lapply(rows, function(r) { + Xj <- X[r, , drop = FALSE] + Zj <- Z[r, , drop = FALSE] + M <- solve(sigma2 * diag(q) + G_child %*% crossprod(Zj), G_child) + XZ <- crossprod(Xj, Zj) + z1 <- colSums(Zj) + list(A = (crossprod(Xj) - XZ %*% M %*% t(XZ)) / sigma2, + b = (colSums(Xj) - drop(XZ %*% M %*% z1)) / sigma2, + c = (length(r) - drop(z1 %*% M %*% z1)) / sigma2) + }) schools <- unique(as.character(school_id)) stats <- lapply(schools, function(s) { js <- which(school_of_child == s) - A <- Reduce(`+`, lapply(js, function(j) { - Xj <- X[rows[[j]], , drop = FALSE] - (crossprod(Xj) - k_j[j] * tcrossprod(sx[j, ])) / sigma2 - })) - b <- colSums(sx[js, , drop = FALSE] * (1 - k_j[js] * T_j[js])) / sigma2 - c <- sum(T_j[js] * (1 - k_j[js] * T_j[js])) / sigma2 - list(A = A, b = b, c = c, n_child = length(js)) + list(A = Reduce(`+`, lapply(per_child[js], `[[`, "A")), + b = Reduce(`+`, lapply(per_child[js], `[[`, "b")), + c = sum(vapply(per_child[js], `[[`, numeric(1L), "c")), + n_child = length(js)) }) names(stats) <- schools stats @@ -68,7 +96,7 @@ lyuSchoolStats <- function(X, school_id, child_id, tau2_child, sigma2) { anova = data.frame(RESI = anova_resi, row.names = term_labels)) } -#' Lyu-Welsh limiting RESI for a three-level random-intercept lmer fit +#' Lyu-Welsh limiting RESI for a three-level lmer fit #' #' Evaluates the g, m -> Inf limit (Lyu & Welsh, 2022) of the per-unit #' covariance of the fixed effects and the corresponding RESI at the fitted @@ -76,7 +104,9 @@ lyuSchoolStats <- function(X, school_id, child_id, tau2_child, sigma2) { #' C = g^{-1} sum_s x_s x_s'. Within-school columns: the school intercept acts #' as a fixed effect, so I_w / N = N^{-1} sum_s (A_s - b_s b_s' / c_s). The #' between and within blocks are asymptotically independent. -#' @param fit A `lmerMod` fit of `y ~ X + (1 | school/child)`. +#' @param fit A `lmerMod` fit with a school random intercept and child-level +#' random effects (intercept and optionally slopes), e.g. +#' `y ~ X + (1 | school/child)`. #' @param school,child Names of the school and child grouping factors in #' `lme4::getME(fit, "flist")`. #' @return List with `coefficients` and `anova` RESI tables, the logical @@ -93,7 +123,7 @@ lyuLimitResi <- function(fit, school = "schoolid", child = "childid:schoolid") { Vb <- vc$tau2_school * solve(crossprod(Xb) / nrow(Xb)) st <- lyuSchoolStats(X[, !between, drop = FALSE], school_id, fl[[child]], - vc$tau2_child, vc$sigma2) + vc$G_child, vc$sigma2, .mixedChildZ(fit, child)) N <- sum(vapply(st, `[[`, numeric(1L), "n_child")) Iw <- Reduce(`+`, lapply(st, function(s) s$A - tcrossprod(s$b) / s$c)) Vw <- solve(Iw / N) @@ -115,7 +145,7 @@ lyuLimitResi <- function(fit, school = "schoolid", child = "childid:schoolid") { fl <- lme4::getME(fit, "flist") vc <- .mixedVarComps(fit, school, child) school_id <- fl[[school]] - st <- lyuSchoolStats(X, school_id, fl[[child]], vc$tau2_child, vc$sigma2) + st <- lyuSchoolStats(X, school_id, fl[[child]], vc$G_child, vc$sigma2, .mixedChildZ(fit, child)) n_s <- vapply(st, `[[`, numeric(1L), "n_child") r <- m / mean(n_s) list(I_s = lapply(st, function(s) { @@ -215,7 +245,9 @@ designAveragedSe <- function(fit, g, m, n_rep = 2000L, #' covariance. RESI and per-unit SE targets are the Lyu-Welsh g, m -> Inf #' limit at the full-data ML estimates ([lyuLimitResi()]). #' -#' @param formula Model formula of the form `y ~ X + (1 | school/child)`. +#' @param formula Model formula with a school random intercept and child-level +#' random effects, e.g. `y ~ X + (1 | school/child)` or +#' `y ~ X + (1 | school) + (year | child:school)`. #' @param data Data frame containing the variables in `formula`. #' @param school,child Names of the school and child id columns of `data`. #' @param n_schools,n_per_site Vectors crossed to form the simulation grid. @@ -252,15 +284,27 @@ hybridPlasmodeSim <- function(formula, data, school = "schoolid", child = "child vc <- .mixedVarComps(truth_fit, school_grp, child_grp) resid_sd <- stats::sigma(truth_fit) - # BLUP pools centred to mean zero and rescaled so their (1/G) variance equals - # the fitted component, undoing BLUP shrinkage; draws are with replacement. - rescale_blup <- function(blup, target_var) { - centered <- blup - mean(blup) - centered * sqrt(target_var / mean(centered^2)) + # BLUP pools centred to mean zero and rescaled so their (1/G) covariance + # equals the fitted component, undoing BLUP shrinkage; draws are with + # replacement (whole rows for vector-valued child effects). + msqrt <- function(S, inverse = FALSE) { + e <- eigen(S, symmetric = TRUE) + d <- pmax(e$values, 0) + d <- if (inverse) ifelse(d > 1e-12 * max(d), 1 / sqrt(d), 0) else sqrt(d) + e$vectors %*% (d * t(e$vectors)) + } + rescale_blup <- function(blup, target_cov) { + centered <- scale(as.matrix(blup), scale = FALSE) + centered %*% msqrt(crossprod(centered) / nrow(centered), inverse = TRUE) %*% + msqrt(as.matrix(target_cov)) } re <- lme4::ranef(truth_fit) - school_pool <- rescale_blup(re[[school_grp]][[1L]], vc$tau2_school) - child_pool <- rescale_blup(re[[child_grp]][[1L]], vc$tau2_child) + school_pool <- drop(rescale_blup(re[[school_grp]][[1L]], vc$tau2_school)) + child_pool <- rescale_blup(re[[child_grp]], vc$G_child) + child_bar <- Filter(function(b) identical(deparse(b[[3L]]), child_grp), + reformulas::findbars(formula)) + if (length(child_bar) != 1L) stop("Expected one random-effects term for ", child_grp, ".") + child_z_formula <- stats::as.formula(call("~", child_bar[[1L]][[2L]])) school_profiles <- levels(data[[school]]) rows_by_school <- split(seq_len(nrow(data)), data[[school]]) @@ -291,9 +335,12 @@ hybridPlasmodeSim <- function(formula, data, school = "schoolid", child = "child generate_outcome <- function(design) { school_effect <- sample(school_pool, nlevels(design[[school]]), replace = TRUE) - child_effect <- sample(child_pool, nlevels(design[[child]]), replace = TRUE) + child_effect <- child_pool[sample.int(nrow(child_pool), nlevels(design[[child]]), + replace = TRUE), , drop = FALSE] + child_part <- rowSums(stats::model.matrix(child_z_formula, data = design) * + child_effect[design[[child]], , drop = FALSE]) fixed_part <- stats::model.matrix(fixed_rhs, data = design) %*% beta - drop(fixed_part) + school_effect[design[[school]]] + child_effect[design[[child]]] + + drop(fixed_part) + school_effect[design[[school]]] + child_part + stats::rnorm(nrow(design), sd = resid_sd) } diff --git a/R/resi.R b/R/resi.R index 8eb9d79..917b560 100644 --- a/R/resi.R +++ b/R/resi.R @@ -770,7 +770,9 @@ resi.lme = function(model.full, alpha = 0.05, nboot = 1000, anova = TRUE, #' cluster-level influence functions (`ci.method` one of `"normal"`, `"qf"`, #' `"cf"`; coefficients get the signed normal CI for `"qf"`). Use #' `vcovfunc = stats::vcov` for model-based or `clubSandwich::vcovCR` (e.g. -#' `vcov.args = list(type = "CR2")`) for cluster-robust intervals. +#' `vcov.args = list(type = "CR2")`) for cluster-robust intervals; +#' cluster-robust intervals use t / F references with g - 1 denominator +#' degrees of freedom (g = number of clusters). #' `ci.design = TRUE` (default) treats the cluster covariate profiles as #' sampled; `FALSE` gives intervals conditional on the observed design. #' `ci.method = "none"` returns point estimates only. ANOVA CIs are for the diff --git a/R/resi_asymptotic.R b/R/resi_asymptotic.R index 2dd6ebb..09de6ed 100644 --- a/R/resi_asymptotic.R +++ b/R/resi_asymptotic.R @@ -458,13 +458,27 @@ m4 <- mean(phi_tilde^4) gamma1 <- m3 / (sqrt(n) * Sigma_R^(3 / 2)) gamma2 <- (m4 / Sigma_R^2 - 3) / n + scale <- 1 + df <- .resi_ref_df(contrast) + # The t-type CF needs the first four moments of sqrt(df / W): df > 4. + if (is.finite(df) && df <= 4) return(.resi_ci_normal_signed(contrast, alpha)) + if (is.finite(df)) { + # Moments of Z * sqrt(df / W), W ~ chi^2_df independent of Z. + b <- .resi_inv_chisq_moment(c(1, 1.5, 2), df) + k2 <- b[1] + k3 <- gamma1 * b[2] + k4 <- (gamma2 + 3) * b[3] - 3 * k2^2 + scale <- sqrt(k2) + gamma1 <- k3 / k2^1.5 + gamma2 <- k4 / k2^2 + } cf_w <- function(p) { z <- qnorm(p) - z + + scale * (z + (gamma1 / 6 ) * (z^2 - 1) + (gamma2 / 24) * (z^3 - 3 * z) - - (gamma1^2 / 36) * (2 * z^3 - 5 * z) + (gamma1^2 / 36) * (2 * z^3 - 5 * z)) } # These are the correct intervals @@ -493,7 +507,7 @@ # sandwich estimates can collapse below 1, shrinking the CI inappropriately. # se <- max(sqrt(as.numeric(Sigma_R) / n), 1 / sqrt(n)) se <- sqrt(as.numeric(Sigma_R) / n) - z <- qnorm(1 - alpha / 2) + z <- .resi_qref(1 - alpha / 2, .resi_ref_df(contrast)) c(LCI = S_signed - z * se, UCI = S_signed + z * se) } @@ -515,7 +529,8 @@ # asymptotically. So P(Stilde >= UCI | S=0) = alpha gives # UCI = sqrt(qchisq(1-alpha, df=m1) / n). # For m1=1: sqrt(qchisq(1-alpha, 1)/n) = qnorm(1-alpha/2)/sqrt(n). - UCI_null <- sqrt(qchisq(1 - alpha, df = m1) / n) + df <- .resi_ref_df(contrast) + UCI_null <- .resi_null_upper(alpha, m1, n, df) if (Shat <= 0) { return(c(LCI = 0, UCI = UCI_null)) @@ -529,7 +544,7 @@ se <- sqrt(pmax(sigma2S, 0) / n) # truncate_ci handles boundary; centered at Shat - bounds <- .resi_truncate_ci(Shat, se, n, m1, alpha) + bounds <- .resi_truncate_ci(Shat, se, n, m1, alpha, df) # When LCI clips to 0, the directional delta-method UCI can underestimate # spread for m1>1 (single-direction 1D normal vs chi(m1) null distribution). @@ -583,25 +598,43 @@ # For m1=1: use pchisq (no imhof precision issues) # For m1>1: use imhof if (m1 == 1L) { - q <- T2_obs / lambda[1] # Exact identity chi^2(1,lambda) = (Z + sqrt(lambda))^2: # P(chi^2(1,lambda) >= q) = pnorm(sqrt(lambda) - sqrt(q)) + pnorm(-sqrt(lambda) - sqrt(q)). # Used for all q and lambda: pnchisq loses precision (or returns 0 in the # tails) once q and lambda reach the hundreds, whereas pnorm is accurate # at any argument. - prob_fn <- function(S_b) { + prob_at <- function(S_b, t) { nc <- nc_fun(S_b) if (!is.finite(nc)) return(1.0) - sq <- sqrt(max(q, 0)) + sq <- sqrt(max(t / lambda[1], 0)) snc <- sqrt(max(nc, 0)) pnorm(snc - sq) + pnorm(-snc - sq) } } else { - prob_fn <- function(S_b) { + prob_at <- function(S_b, t) { nc <- nc_fun(S_b) # Cap individual non-centrality components to avoid imhof overflow nc <- pmin(nc, 1e10 * max(T2_obs, 1)) - suppressWarnings(CompQuadForm::imhof(T2_obs, lambda = lambda, delta = nc)$Qq) + suppressWarnings(CompQuadForm::imhof(t, lambda = lambda, delta = nc)$Qq) + } + } + df <- .resi_ref_df(contrast) + prob_fn <- if (!is.finite(df)) { + function(S_b) prob_at(S_b, T2_obs) + } else { + # t-type reference: the Gaussian noise of Q is replaced by t_df noise, + # Q = sum_k lambda_k (Z_k sqrt(df / W) + sqrt(nc_k))^2, W ~ chi^2_df, leaving + # the signal unscaled (Sigma already carries the variance-estimation + # uncertainty). Given W = w this is the chi-square-reference law at + # S_b sqrt(w / df) exceeding T2_obs w / df; under H0 T2 / m1 ~ F(m1, df). + # Averaged over W with a fixed Gauss-Laguerre rule (adaptive integrate() + # failed in some replicates). + nodes <- .resi_w_nodes(df) + w_scaled <- nodes$w / df + function(S_b) { + sum(nodes$p * vapply(w_scaled, function(w) { + min(max(prob_at(S_b * sqrt(w), T2_obs * w), 0), 1) + }, numeric(1L))) } } @@ -646,7 +679,7 @@ # Null upper bound: (1-alpha) quantile of Stilde under H0. # Under H0, n*Stilde^2 ~ chi^2_{m1} asymptotically, so # UCI_null = sqrt(qchisq(1-alpha, df=m1) / n). - UCI_null <- sqrt(qchisq(1 - alpha, df = m1) / n) + UCI_null <- .resi_null_upper(alpha, m1, n, df) if (p0 >= 1 - alpha / 2) { # T2_obs is in the lower alpha/2 tail of the null distribution; @@ -689,6 +722,7 @@ #' Sigma_R and delta_k scaled so that sum delta_k^2 = n*S_b^2. #' @noRd .resi_ci_cf <- function(contrast, alpha = 0.05) { + df <- .resi_ref_df(contrast) Sigma_R <- contrast$Sigma_R R_beta <- contrast$R_beta Stilde <- contrast$Stilde @@ -751,14 +785,55 @@ # can diverge near S_b = 0 (gamma1 is large for the central distribution), # so we use the exact chi-square approximation there -- the same approach # as the QF CI. CF is only applied for the inversion at nonzero S_b. - UCI_null <- sqrt(qchisq(1 - alpha, df = m1) / n) + UCI_null <- .resi_null_upper(alpha, m1, n, df) - # P(T2 >= T2_obs | S = 0) under chi^2_{m1} approximation - p0 <- pchisq(T2_obs, df = m1, lower.tail = FALSE) + # P(T2 >= T2_obs | S = 0) under the chi^2_{m1} (or m1 * F(m1, df)) approximation + p0 <- .resi_pnull(T2_obs, m1, df) # Degenerate: no signal at all if (T2_obs == 0) return(c(LCI = 0, UCI = UCI_null)) + if (is.finite(df)) { + # t-type reference (as in .resi_ci_qf): t_df noise, unscaled signal. Given + # W = w, P(T2 >= T2_obs) is the chi-square-reference probability at + # S_b sqrt(w / df) of exceeding T2_obs w / df; the CDF is read off the CF + # quantile function on a probability grid and averaged over + # W ~ chi^2_df with a Gauss-Laguerre rule. + pgrid <- pnorm(seq(-4, 4, length.out = 321L)) + mid <- 161L + nodes <- .resi_w_nodes(df) + w_scaled <- nodes$w / df + cdf_at <- function(S_b, x) { + q <- cf_quant(S_b, pgrid) + if (anyNA(q)) return(NA_real_) + # The CF polynomial can be non-monotone in the far tails: enforce + # monotonicity outward from the median. + q[mid:321L] <- cummax(q[mid:321L]) + q[mid:1L] <- cummin(q[mid:1L]) + stats::approx(q, pgrid, x, yleft = 0, yright = 1, ties = "ordered")$y + } + prob_fn <- function(S_b) { + 1 - sum(nodes$p * vapply(w_scaled, function(w) cdf_at(S_b * sqrt(w), T2_obs * w), numeric(1L))) + } + p0 <- .resi_pnull(T2_obs, m1, df) + LCI <- if (p0 >= alpha / 2) 0 else tryCatch( + uniroot(function(s) prob_fn(s) - alpha / 2, lower = 0, upper = Stilde, + tol = se_S * 1e-3, extendInt = "upX")$root, + error = function(e) 0) + if (p0 >= 1 - alpha / 2) return(c(LCI = max(LCI, 0), UCI = UCI_null)) + upper_search <- Shat + se_S * c(3, 6, 12, 25, 50, 100) * qnorm(1 - alpha / 2) + bracket_up <- NA_real_ + for (up in upper_search) { + pup <- prob_fn(up) + if (!is.na(pup) && pup >= 1 - alpha / 2) { bracket_up <- up; break } + } + UCI <- if (is.na(bracket_up)) UCI_null else tryCatch( + uniroot(function(s) prob_fn(s) - (1 - alpha / 2), lower = Stilde, + upper = bracket_up, tol = se_S * 1e-3)$root, + error = function(e) UCI_null) + return(c(LCI = max(LCI, 0), UCI = UCI)) + } + # ---- Lower bound ---- # LCI = 0 when the null distribution already has >= alpha/2 probability above T2_obs. if (p0 >= alpha / 2) { @@ -1494,8 +1569,8 @@ resi_pe_asymptotic <- function(model.full, #' Truncated CI for unsigned RESI (Algorithm 1, Zhang et al. 2025) #' @noRd -.resi_truncate_ci <- function(Shat, se, n, m1, alpha = 0.05) { - z1 <- qnorm(1 - alpha / 2) +.resi_truncate_ci <- function(Shat, se, n, m1, alpha = 0.05, df = Inf) { + z1 <- .resi_qref(1 - alpha / 2, df) SL <- Shat - z1 * se SU <- Shat + z1 * se @@ -1503,12 +1578,52 @@ resi_pe_asymptotic <- function(model.full, # probability mass at/below zero under H0: P(T^2 > n*Shat^2 | S=0) # Under H0, T^2 ~ chi^2_{m1}, so P(T^2 > m1 + n*Shat^2) (since Shat^2 = (T^2-m1)/n) - gamma_p <- pchisq(m1 + n * Shat^2, df = m1, lower.tail = FALSE) + gamma_p <- .resi_pnull(m1 + n * Shat^2, m1, df) if (gamma_p < alpha / 2) { - SU <- Shat + qnorm(1 - (alpha - gamma_p)) * se + SU <- Shat + .resi_qref(1 - (alpha - gamma_p), df) * se } else { - SU <- Shat + qnorm(1 - alpha) * se + SU <- Shat + .resi_qref(1 - alpha, df) * se } c(0, SU) } + +# [AI-generated: GitHub Copilot, 2026-11-17] +# [Prompt summary: t / F(m1, df) reference distributions for RESI CIs whose +# covariance is estimated from df + 1 clusters (CR2 mixed-model intervals).] +# Reference distributions. `df` is the denominator degrees of freedom of the +# variance estimate (contrast$df; Inf/NULL = known variance, i.e. the normal and +# chi-square references). A finite df gives t and F(m1, df) references, used +# when the covariance is estimated from df + 1 clusters (cluster-robust CR2). +.resi_ref_df <- function(contrast) if (is.null(contrast$df)) Inf else contrast$df + +.resi_qref <- function(p, df) if (is.finite(df)) qt(p, df) else qnorm(p) + +# P(T^2 >= x) under H0 with Sigma_R = I. +.resi_pnull <- function(x, m1, df) { + if (is.finite(df)) pf(x / m1, m1, df, lower.tail = FALSE) else + pchisq(x, df = m1, lower.tail = FALSE) +} + +# (1 - alpha) quantile of Stilde under H0. +.resi_null_upper <- function(alpha, m1, n, df) { + if (is.finite(df)) sqrt(m1 * qf(1 - alpha, m1, df) / n) else sqrt(qchisq(1 - alpha, df = m1) / n) +} + +# E[(df / W)^r], W ~ chi^2_df (finite for r < df / 2). +# Generalized Gauss-Laguerre rule for E[h(W)], W ~ chi^2_df (Golub-Welsch on +# X = W / 2 ~ Gamma(df / 2, 1)), used to average over the t-type noise in the +# finite-df QF and CF intervals. With 20 nodes the shifted-t tail +# probabilities are accurate to < 4e-4 for df >= 4 and < 1e-5 for df >= 9. +.resi_w_nodes <- function(df, K = 20L) { + a <- df / 2 + k <- seq_len(K - 1L) + J <- diag(2 * (0:(K - 1L)) + a) + off <- sqrt(k * (k + a - 1)) + J[cbind(k, k + 1L)] <- off + J[cbind(k + 1L, k)] <- off + e <- eigen(J, symmetric = TRUE) + list(w = 2 * e$values, p = e$vectors[1L, ]^2) +} + +.resi_inv_chisq_moment <- function(r, df) exp(r * log(df / 2) + lgamma(df / 2 - r) - lgamma(df / 2)) diff --git a/R/resi_mixed_ci.R b/R/resi_mixed_ci.R index aa5272f..1c0277b 100644 --- a/R/resi_mixed_ci.R +++ b/R/resi_mixed_ci.R @@ -1,3 +1,7 @@ +# [AI-generated: GitHub Copilot, 2026-11-15] +# [Prompt summary: asymptotic RESI CIs (normal/QF/CF; model-based and CR2) for +# lmerMod and lme fits, coverage of the Lyu-Welsh and fixed-m targets.] + # Asymptotic RESI confidence intervals for lmerMod and nlme::lme fits with random effects # nested in an outermost cluster (derivation: AIgams notes/resi_mixed_ci.qmd). # @@ -286,6 +290,10 @@ #' @param cluster Name of the outermost grouping factor. #' @param n_level_coef,n_level_anova Optional named grouping-factor names #' whose counts are `n_coef`/`n_anova` (the `n level` columns). +#' @param ref.df Denominator degrees of freedom of the reference +#' distributions (t / F instead of normal / chi-square); `Inf` for the +#' normal / chi-square references. `NULL` (default) uses g - 1 (g = number +#' of clusters) when `robust` and `Inf` otherwise. #' @return A list with, for each requested `ci.method`, `coefficients` and #' `anova` matrices of LCI and UCI, and `se`, the estimated SD of each #' one-degree-of-freedom RESI estimate. @@ -294,9 +302,11 @@ .resi_ci_mixed <- function(fit, Vhat, robust, n_coef, n_anova = NULL, ci.method = c("normal", "qf", "cf"), alpha = 0.05, design = TRUE, cluster = NULL, - n_level_coef = NULL, n_level_anova = NULL) { + n_level_coef = NULL, n_level_anova = NULL, + ref.df = NULL) { ci.method <- match.arg(ci.method, several.ok = TRUE) base <- .mixedCiBase(fit, cluster) + if (is.null(ref.df)) ref.df <- if (robust) nlevels(base$cluster) - 1 else Inf gls <- .mixedCiGls(base, base$theta, base$sigma) pieces <- .mixedCiClusterPieces(base, gls) beta <- base$beta @@ -350,8 +360,10 @@ cn <- contrasts[[i]] idx <- (ends[i] - nrow(cn$L) + 1L):ends[i] Jpsi <- if (robust) NULL else Jpsi_all[idx, , drop = FALSE] - .mixedCiContrast(cn$L, cn$n, beta, Vhat, gls$info, pieces, robust, - design, cn$counts, Jpsi, if (robust) NULL else Vpsi) + ct <- .mixedCiContrast(cn$L, cn$n, beta, Vhat, gls$info, pieces, robust, + design, cn$counts, Jpsi, if (robust) NULL else Vpsi) + ct$df <- ref.df + ct }) out <- lapply(setNames(ci.method, ci.method), function(method) { res <- lapply(seq_along(cts), function(i) { diff --git a/R/resi_pe_mixed.R b/R/resi_pe_mixed.R index 2adae3a..d1cefdc 100644 --- a/R/resi_pe_mixed.R +++ b/R/resi_pe_mixed.R @@ -32,7 +32,30 @@ } list(X = X, assign = attr(X, "assign"), terms = attr(stats::terms( if (engine == "lmerMod") reformulas::nobars(formula(model.full)) else formula(model.full) - ), "term.labels"), groups = groups, data = data) + ), "term.labels"), groups = groups, data = data, + slopes = .resiMixedSlopeLevels(model.full, engine, colnames(X))) +} + +# [AI-generated: GitHub Copilot, 2026-11-17] +# [Prompt summary: a term with a random slope at level k is normalized by the +# number of level-k units (SNV decision for Model B).] +# For each fixed-effect column, the grouping factors at which it has a random +# slope (random-effect columns are matched to fixed-effect columns by name; +# random intercepts are ignored). +.resiMixedSlopeLevels <- function(model.full, engine, x_names) { + re_cols <- if (engine == "lmerMod") { + lme4::getME(model.full, "cnms") + } else { + re <- model.full$modelStruct$reStruct + setNames(lapply(seq_along(re), function(k) colnames(as.matrix(re[[k]]))), names(re)) + } + out <- setNames(rep(list(character(0)), length(x_names)), x_names) + for (k in seq_along(re_cols)) { + for (col in setdiff(intersect(re_cols[[k]], x_names), "(Intercept)")) { + out[[col]] <- union(out[[col]], names(re_cols)[[k]]) + } + } + out } .resiMixedHasVariation <- function(x) { @@ -188,6 +211,21 @@ ) n_levels <- ifelse(is_between_cluster, top_cluster_name, selected_level) names(n_levels) <- names(term_levels) + # A random slope at a coarser level than the term's n level drives the + # variance of its coefficient, so the term is normalized by the number of + # units at that level (e.g. g for a school-level random slope). + if (!is.null(design$slopes)) { + for (term in names(term_levels)[-1L]) { + cols <- colnames(X)[assign == match(term, term_labels)] + slope_levels <- unique(unlist(design$slopes[cols])) + idx <- match(slope_levels, hierarchy_names) + idx <- idx[!is.na(idx)] + if (length(idx) && min(idx) < match(n_levels[[term]], hierarchy_names)) { + n_levels[[term]] <- hierarchy_names[[min(idx)]] + term_ns[[term]] <- hierarchy_counts[[min(idx)]] + } + } + } } coefficient_terms <- character(ncol(X)) @@ -333,7 +371,11 @@ #' coefficient and ANOVA term. If `NULL` (default), the count is #' term-specific (Lyu & Welsh, 2022): terms constant within the outermost #' grouping factor (including the intercept) use the number of outermost -#' groups, and all other terms use the number of groups at `level`. +#' groups, and all other terms use the number of groups at `level`. A term +#' with a random slope at a coarser grouping factor than this uses the +#' number of groups of the coarsest such factor (e.g. the number of schools +#' for `year` in `(year | school)`), since that variance component drives +#' the variance of its coefficient. #' @param level Random-effect hierarchy level or grouping-factor name whose #' group count normalizes terms that vary within the outermost grouping #' factor. Numeric levels are ordered from outermost to innermost grouping diff --git a/man/designAveragedSe.Rd b/man/designAveragedSe.Rd index 461b039..d5eb33b 100644 --- a/man/designAveragedSe.Rd +++ b/man/designAveragedSe.Rd @@ -14,7 +14,9 @@ designAveragedSe( ) } \arguments{ -\item{fit}{A `lmerMod` fit of `y ~ X + (1 | school/child)`.} +\item{fit}{A `lmerMod` fit with a school random intercept and child-level +random effects (intercept and optionally slopes), e.g. +`y ~ X + (1 | school/child)`.} \item{g}{Number of schools.} diff --git a/man/expectedDesignResi.Rd b/man/expectedDesignResi.Rd index 3420f05..c4f29fc 100644 --- a/man/expectedDesignResi.Rd +++ b/man/expectedDesignResi.Rd @@ -7,7 +7,9 @@ expectedDesignResi(fit, m, school = "schoolid", child = "childid:schoolid") } \arguments{ -\item{fit}{A `lmerMod` fit of `y ~ X + (1 | school/child)`.} +\item{fit}{A `lmerMod` fit with a school random intercept and child-level +random effects (intercept and optionally slopes), e.g. +`y ~ X + (1 | school/child)`.} \item{m}{Average number of students per school.} diff --git a/man/hybridPlasmodeSim.Rd b/man/hybridPlasmodeSim.Rd index 48375ea..0e2a887 100644 --- a/man/hybridPlasmodeSim.Rd +++ b/man/hybridPlasmodeSim.Rd @@ -20,7 +20,9 @@ hybridPlasmodeSim( ) } \arguments{ -\item{formula}{Model formula of the form `y ~ X + (1 | school/child)`.} +\item{formula}{Model formula with a school random intercept and child-level +random effects, e.g. `y ~ X + (1 | school/child)` or +`y ~ X + (1 | school) + (year | child:school)`.} \item{data}{Data frame containing the variables in `formula`.} diff --git a/man/lyuLimitResi.Rd b/man/lyuLimitResi.Rd index 12bfef5..a31ea38 100644 --- a/man/lyuLimitResi.Rd +++ b/man/lyuLimitResi.Rd @@ -2,12 +2,14 @@ % Please edit documentation in R/mixed_simulations.R \name{lyuLimitResi} \alias{lyuLimitResi} -\title{Lyu-Welsh limiting RESI for a three-level random-intercept lmer fit} +\title{Lyu-Welsh limiting RESI for a three-level lmer fit} \usage{ lyuLimitResi(fit, school = "schoolid", child = "childid:schoolid") } \arguments{ -\item{fit}{A `lmerMod` fit of `y ~ X + (1 | school/child)`.} +\item{fit}{A `lmerMod` fit with a school random intercept and child-level +random effects (intercept and optionally slopes), e.g. +`y ~ X + (1 | school/child)`.} \item{school, child}{Names of the school and child grouping factors in `lme4::getME(fit, "flist")`.} diff --git a/man/resi.Rd b/man/resi.Rd index 9e4dcbf..e70c283 100644 --- a/man/resi.Rd +++ b/man/resi.Rd @@ -433,7 +433,9 @@ models whose random effects are nested in an outermost cluster. CIs use cluster-level influence functions (`ci.method` one of `"normal"`, `"qf"`, `"cf"`; coefficients get the signed normal CI for `"qf"`). Use `vcovfunc = stats::vcov` for model-based or `clubSandwich::vcovCR` (e.g. -`vcov.args = list(type = "CR2")`) for cluster-robust intervals. +`vcov.args = list(type = "CR2")`) for cluster-robust intervals; +cluster-robust intervals use t / F references with g - 1 denominator +degrees of freedom (g = number of clusters). `ci.design = TRUE` (default) treats the cluster covariate profiles as sampled; `FALSE` gives intervals conditional on the observed design. `ci.method = "none"` returns point estimates only. ANOVA CIs are for the diff --git a/man/resi_pe.Rd b/man/resi_pe.Rd index daaab40..1e6b6ee 100644 --- a/man/resi_pe.Rd +++ b/man/resi_pe.Rd @@ -258,7 +258,11 @@ resi_pe(...) coefficient and ANOVA term. If `NULL` (default), the count is term-specific (Lyu & Welsh, 2022): terms constant within the outermost grouping factor (including the intercept) use the number of outermost -groups, and all other terms use the number of groups at `level`.} +groups, and all other terms use the number of groups at `level`. A term +with a random slope at a coarser grouping factor than this uses the +number of groups of the coarsest such factor (e.g. the number of schools +for `year` in `(year | school)`), since that variance component drives +the variance of its coefficient.} \item{level}{Random-effect hierarchy level or grouping-factor name whose group count normalizes terms that vary within the outermost grouping diff --git a/tests/testthat/test-resi-mixed-ci.R b/tests/testthat/test-resi-mixed-ci.R index 91645f4..51389b6 100644 --- a/tests/testthat/test-resi-mixed-ci.R +++ b/tests/testthat/test-resi-mixed-ci.R @@ -100,6 +100,15 @@ test_that("resi() on lmerMod returns ordered RESI intervals for each method", { robust <- resi(fit, vcov.args = list(type = "CR2"), cluster = "schoolid", ci.method = "normal", level = 2) check(robust) + # CR2 intervals use the t(g - 1) reference: signed normal widths scale by + # qt / qnorm relative to the normal reference. + Vcr2 <- .mixedCiCR2(fit, "schoolid") + n_coef <- setNames(robust$coefficients$n, rownames(robust$coefficients)) + ci_z <- .resi_ci_mixed(fit, Vcr2, TRUE, n_coef, ci.method = "normal", + cluster = "schoolid", ref.df = Inf)$normal$coefficients + expect_equal(robust$coefficients[["97.5%"]] - robust$coefficients[["2.5%"]], + unname(ci_z[, 2] - ci_z[, 1]) * qt(0.975, 19) / qnorm(0.975), + tolerance = 1e-6) expect_equal(robust$coefficients$Robust.SE, unname(sqrt(diag(.mixedCiCR2(fit, "schoolid"))))) expect_warning(none <- resi(fit, vcovfunc = stats::vcov, ci.method = "none", level = 2), diff --git a/tests/testthat/test-resi-mixed-scale.R b/tests/testthat/test-resi-mixed-scale.R index 5912858..2ab5aca 100644 --- a/tests/testthat/test-resi-mixed-scale.R +++ b/tests/testthat/test-resi-mixed-scale.R @@ -73,3 +73,29 @@ test_that("nlme mixed-model RESI uses the same normalizer API", { expect_equal(pe$coefficients["age", "Var prop Subject"], 0) expect_equal(pe$anova["Sex", "Var prop Subject"], 1) }) + +test_that("a random slope at a coarser level sets the term's n to that level's count", { + skip_if_not_installed("lme4") + skip_if_not_installed("nlme") + skip_if_not_installed("mlmRev") + egsingle <- local({ + env <- new.env() + utils::data("egsingle", package = "mlmRev", envir = env) + env$egsingle + }) + slope_school <- suppressWarnings(lme4::lmer( + math ~ year + female + size + (year | schoolid) + (1 | childid:schoolid), data = egsingle)) + pe <- resi_pe(slope_school, vcovfunc = stats::vcov, level = 2) + expect_equal(pe$coefficients[c("year", "femaleMale"), "n"], c(60, 1721)) + expect_equal(pe$coefficients["year", "n level"], "schoolid") + expect_equal(pe$anova["year", "n"], 60) + expect_equal(pe$coefficients["year", "Variation level"], "observation within childid:schoolid") + + slope_child <- lme4::lmer( + math ~ year + female + size + (1 | schoolid) + (year | childid:schoolid), data = egsingle) + expect_equal(resi_pe(slope_child, vcovfunc = stats::vcov, level = 2)$coefficients["year", "n"], 1721) + + slope_lme <- nlme::lme(math ~ year + female + size, + random = list(schoolid = ~ year, childid = ~ 1), data = egsingle) + expect_equal(resi_pe(slope_lme, vcovfunc = stats::vcov, level = 2)$coefficients["year", "n"], 60) +}) diff --git a/tests/testthat/test-resi_asymptotic.R b/tests/testthat/test-resi_asymptotic.R index bca769b..a9a9bfe 100644 --- a/tests/testthat/test-resi_asymptotic.R +++ b/tests/testthat/test-resi_asymptotic.R @@ -160,6 +160,23 @@ test_that("QF CI for one df is correct for large and moderate noncentrality", { expect_equal(tail_at(ci[[2]]), 0.975, tolerance = 1e-3) }) +test_that("finite-df QF and CF invert the shifted-t test and match signed normal-t", { + # t-type reference: T = sqrt(n / Sigma_R) * S + T_df, so the 1-df bounds + # solve P(|T_df + delta(S)| >= t_obs) = alpha / 2 and 1 - alpha / 2. + ct <- list(m1 = 1L, n = 200, R_beta = 0.4, Stilde = 0.4, Sigma_R = matrix(1.3), df = 9) + t_obs <- sqrt(ct$n / 1.3) * ct$Stilde + tail_at <- function(s) { + d <- sqrt(ct$n / 1.3) * s + pt(t_obs - d, 9, lower.tail = FALSE) + pt(-t_obs - d, 9) + } + for (ci in list(.resi_ci_qf(ct), .resi_ci_cf(ct))) { + expect_lt(abs(tail_at(ci[[1]]) - 0.025), 5e-4) + expect_lt(abs(tail_at(ci[[2]]) - 0.975), 5e-4) + } + expect_equal(unname(.resi_ci_qf(ct)), + unname(.resi_ci_normal_signed(ct)), tolerance = 1e-3) +}) + # =========================================================================== # 7. CI bounds agree on coefficients: normal and QF both use signed normal From 8b0dbce025c28cfb14e4832305417dffb86141ad Mon Sep 17 00:00:00 2001 From: simonvandekar Date: Thu, 19 Nov 2026 09:46:30 -0600 Subject: [PATCH 6/6] pkgdown: add hybridPlasmodeSim to reference index Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- _pkgdown.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/_pkgdown.yml b/_pkgdown.yml index fd12de4..1202dcb 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -72,6 +72,7 @@ reference: - title: Simulation functions desc: Functions used for evaluating new RESI estimators and CI methods. - contents: + - hybridPlasmodeSim - insurancePlasmodeSim - simCalibrationFigures - simCalibrationSim