From cca18e60a97157840c5a29dfada2ac54c26b02c7 Mon Sep 17 00:00:00 2001 From: simonvandekar Date: Thu, 19 Nov 2026 08:11:33 -0600 Subject: [PATCH] Add resi_pe() for mgcv gam/bam fits Smooth-term RESI from mgcv's Vp Wald statistic with Ref.df (f2S, or chisq2S when the scale is known); parametric terms via t2S/z2S; terms tested with mgcv's random-effect test (bs = 're', shrinkage, select = TRUE) return NA. resi() errors informatively (CIs not yet implemented). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- DESCRIPTION | 2 + NAMESPACE | 2 + NEWS.md | 2 + R/resi_pe_gam.R | 96 +++++++++++++++++++++++++++++++ man/resi.Rd | 9 ++- man/resi_pe.Rd | 30 +++++++++- tests/testthat/test-resi_pe_gam.R | 38 ++++++++++++ 7 files changed, 177 insertions(+), 2 deletions(-) create mode 100644 R/resi_pe_gam.R create mode 100644 tests/testthat/test-resi_pe_gam.R diff --git a/DESCRIPTION b/DESCRIPTION index 3c66fef..7b2f651 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -37,6 +37,7 @@ Collate: 'omnibus.R' 'simulations.R' 'resi_asymptotic.R' + 'resi_pe_gam.R' Imports: aod, boot, @@ -51,6 +52,7 @@ Imports: splines Suggests: gee, + mgcv, geepack, robustbase, reformulas, diff --git a/NAMESPACE b/NAMESPACE index bc0774d..ab8b3da 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -13,6 +13,7 @@ S3method(print,resi) S3method(print,summary_resi) S3method(resi,coxph) S3method(resi,default) +S3method(resi,gam) S3method(resi,gee) S3method(resi,geeglm) S3method(resi,glm) @@ -30,6 +31,7 @@ S3method(resi,zeroinfl) S3method(resi_pe,coxph) S3method(resi_pe,default) S3method(resi_pe,emmGrid) +S3method(resi_pe,gam) S3method(resi_pe,gee) S3method(resi_pe,geeglm) S3method(resi_pe,glm) diff --git a/NEWS.md b/NEWS.md index 34ca298..34237de 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # RESI (development version) +- Added `resi_pe()` for `mgcv::gam` and `mgcv::bam` fits. RESI for smooth terms uses mgcv's Wald statistic (`Vp`) with `Ref.df` (`f2S`, or `chisq2S` when the scale is known). Parametric terms use `t2S`/`z2S`. Terms tested by mgcv's random-effect test (`bs = "re"`, shrinkage bases, `select = TRUE`) return `NA` with a warning. `resi()` for these models gives an informative error; confidence intervals are not yet implemented. + # RESI 1.5.1.9001 - Fixed `resi_pe.lmerMod()` handling for spline terms like `ns(Days, 3)` by reconstructing the auxiliary fixed-effects model data from the original model call and replacing deprecated `lme4::nobars` usage with `reformulas::nobars`. diff --git a/R/resi_pe_gam.R b/R/resi_pe_gam.R new file mode 100644 index 0000000..635a575 --- /dev/null +++ b/R/resi_pe_gam.R @@ -0,0 +1,96 @@ +#' @describeIn resi_pe RESI point estimation for generalized additive models +#' (\code{mgcv::gam} and \code{mgcv::bam} fits) +#' @details For \code{gam} and \code{bam} models, the RESI is computed from +#' the Wald statistics reported by \code{mgcv::summary.gam}. These use the +#' Bayesian posterior covariance \code{Vp}, so \code{vcovfunc} is not used. +#' Parametric coefficients use \code{\link{t2S}} (or \code{\link{z2S}} when +#' the scale parameter is known). Smooth terms use \code{\link{f2S}} with the +#' reference degrees of freedom \code{Ref.df} and the residual degrees of +#' freedom \code{n - sum(edf)} (or \code{\link{chisq2S}} when the scale is +#' known). The smooth-term RESI estimates the RESI of the population +#' smooth function (net of the other terms); when that function is well +#' represented by the basis, it does not depend on the basis size or the +#' penalty. Penalized terms without an unpenalized null space +#' (\code{bs = "re"}, shrinkage bases, or \code{select = TRUE}) are tested by +#' mgcv with a different statistic, so their RESI is \code{NA}. The overall +#' test is not computed for these models. +#' @export +resi_pe.gam <- function(model.full, data, anova = TRUE, coefficients = TRUE, + unbiased = TRUE, ...) { + if (!requireNamespace("mgcv", quietly = TRUE)) + stop("\nPackage 'mgcv' is required for gam and bam models") + s <- mgcv::summary.gam(model.full) + n <- length(model.full$y) + rdf <- model.full$df.residual + output <- list(model.full = list(call = model.full$call, + formula = formula(model.full)), + model.reduced = NULL) + est <- c() + + if (coefficients) { + pt <- as.data.frame(s$p.table) + pt$RESI <- if ("t value" %in% colnames(pt)) { + suppressWarnings(t2S(pt[, "t value"], rdf, n, unbiased)) + } else { + suppressWarnings(z2S(pt[, "z value"], n, unbiased)) + } + output$coefficients <- pt + est <- c(est, stats::setNames(pt$RESI, rownames(pt))) + } + + if (anova) { + stat_name <- if (isTRUE(model.full$scale.estimated)) "F" else "Chisq" + pv_name <- if (stat_name == "F") "Pr(>F)" else "Pr(>Chisq)" + stat_col <- if (stat_name == "F") "F" else "Chi.sq" + rows <- list() + if (!is.null(s$pTerms.table) && nrow(s$pTerms.table) > 0) { + p <- s$pTerms.table + rows$p <- data.frame(edf = NA_real_, Df = p[, "df"], stat = p[, stat_col], + pval = p[, "p-value"], row.names = rownames(p)) + } + if (!is.null(s$s.table) && nrow(s$s.table) > 0) { + sm <- s$s.table + rows$s <- data.frame(edf = sm[, "edf"], Df = sm[, "Ref.df"], stat = sm[, stat_col], + pval = sm[, "p-value"], row.names = rownames(sm)) + } + tab <- do.call(rbind, unname(rows)) + if (!is.null(tab)) { + tab$RESI <- if (stat_name == "F") { + f2S(tab$stat, tab$Df, rdf, n) + } else { + chisq2S(tab$stat, tab$Df, n) + } + # mgcv tests smooths without an unpenalized null space with a + # different statistic (Wood, 2013b), which has no RESI conversion + # (bs = "re", shrinkage bases, select = TRUE), so these get NA. + re_test <- vapply(model.full$smooth, function(sm) { + !isTRUE(sm$fixed) && identical(as.integer(sm$null.space.dim), 0L) + }, logical(1L)) + no_null <- vapply(model.full$smooth, `[[`, character(1L), "label")[re_test] + if (length(no_null)) { + tab[rownames(tab) %in% no_null, "RESI"] <- NA_real_ + warning("\nRESI is not computed for smooth terms without an unpenalized ", + "null space: ", paste(no_null, collapse = ", ")) + } + colnames(tab)[3:4] <- c(stat_name, pv_name) + attr(tab, "heading") <- "Analysis of Deviance Table (Wald tests from mgcv::summary.gam)\n" + class(tab) <- c("anova_resi", "anova", "data.frame") + output$anova <- tab + est <- c(est, stats::setNames(tab$RESI, rownames(tab))) + } + } + + output$estimates <- est + output$naive.var <- TRUE + class(output) <- c("resi", "list") + output +} + +#' @describeIn resi RESI point estimates for generalized additive models. +#' Confidence intervals are not yet available for \code{gam} and \code{bam} +#' fits; use \code{\link{resi_pe}}. +#' @export +resi.gam <- function(model.full, ...) { + stop("\nConfidence intervals are not yet implemented for gam and bam models. ", + "Use resi_pe() for point estimates.") +} diff --git a/man/resi.Rd b/man/resi.Rd index 62e05c3..2f2ebaa 100644 --- a/man/resi.Rd +++ b/man/resi.Rd @@ -1,5 +1,5 @@ % Generated by roxygen2: do not edit by hand -% Please edit documentation in R/resi.R +% Please edit documentation in R/resi.R, R/resi_pe_gam.R \name{resi} \alias{resi} \alias{resi.default} @@ -18,6 +18,7 @@ \alias{resi.lme} \alias{resi.lmerMod} \alias{resi.glmmTMB} +\alias{resi.gam} \title{Robust Effect Size Index (RESI) point and interval estimation for models} \usage{ resi(model.full, ...) @@ -291,6 +292,8 @@ resi(model.full, ...) vcov.args = list(), ... ) + +\method{resi}{gam}(model.full, ...) } \arguments{ \item{model.full}{\code{lm, glm, nls, survreg, coxph, hurdle, zeroinfl, gee, geeglm} or \code{lme} model object.} @@ -420,6 +423,10 @@ and then try rerunning \code{resi}. \item \code{resi(glmmTMB)}: RESI point and interval estimation for glmmTMB models - Gaussian only +\item \code{resi(gam)}: RESI point estimates for generalized additive models. +Confidence intervals are not yet available for \code{gam} and \code{bam} +fits; use \code{\link{resi_pe}}. + }} \examples{ ## for timing purposes, a small number of bootstrap replicates is used in the diff --git a/man/resi_pe.Rd b/man/resi_pe.Rd index 50f855f..8fea3f3 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_gam.R \name{resi_pe} \alias{resi_pe} \alias{resi_pe.default} @@ -19,6 +19,7 @@ \alias{resi_pe.lmerMod} \alias{resi_pe.glmmTMB} \alias{resi_pe.emmGrid} +\alias{resi_pe.gam} \title{Robust Effect Size Index (RESI) Point Estimation} \usage{ resi_pe(...) @@ -213,6 +214,15 @@ resi_pe(...) ) \method{resi_pe}{emmGrid}(object, model, N = NULL, unbiased = TRUE, ...) + +\method{resi_pe}{gam}( + model.full, + data, + anova = TRUE, + coefficients = TRUE, + unbiased = TRUE, + ... +) } \arguments{ \item{...}{Ignored.} @@ -284,6 +294,21 @@ For GEE (\code{geeglm}) models, a longitudinal RESI (L-RESI) and a cross-section per-measurement RESI (CS-RESI) is estimated. The longitudinal RESI takes the specified clustering into account, while the cross-sectional RESI is estimated using a model where each measurement is its own cluster. + +For \code{gam} and \code{bam} models, the RESI is computed from +the Wald statistics reported by \code{mgcv::summary.gam}. These use the +Bayesian posterior covariance \code{Vp}, so \code{vcovfunc} is not used. +Parametric coefficients use \code{\link{t2S}} (or \code{\link{z2S}} when +the scale parameter is known). Smooth terms use \code{\link{f2S}} with the +reference degrees of freedom \code{Ref.df} and the residual degrees of +freedom \code{n - sum(edf)} (or \code{\link{chisq2S}} when the scale is +known). The smooth-term RESI estimates the RESI of the population +smooth function (net of the other terms); when that function is well +represented by the basis, it does not depend on the basis size or the +penalty. Penalized terms without an unpenalized null space +(\code{bs = "re"}, shrinkage bases, or \code{select = TRUE}) are tested by +mgcv with a different statistic, so their RESI is \code{NA}. The overall +test is not computed for these models. } \section{Methods (by class)}{ \itemize{ @@ -321,6 +346,9 @@ using a model where each measurement is its own cluster. \item \code{resi_pe(emmGrid)}: RESI point estimation for emmeans object +\item \code{resi_pe(gam)}: RESI point estimation for generalized additive models +(\code{mgcv::gam} and \code{mgcv::bam} fits) + }} \examples{ # This function produces point estimates for the RESI. The resi function will diff --git a/tests/testthat/test-resi_pe_gam.R b/tests/testthat/test-resi_pe_gam.R new file mode 100644 index 0000000..238d17b --- /dev/null +++ b/tests/testthat/test-resi_pe_gam.R @@ -0,0 +1,38 @@ +test_that("resi_pe.gam converts mgcv Wald statistics", { + skip_if_not_installed("mgcv") + ins <- RESI::insurance + ins$region <- factor(ins$region) + b <- mgcv::gam(log10(charges) ~ smoker + region + s(age) + s(bmi), + data = ins, method = "REML") + s <- mgcv::summary.gam(b) + r <- resi_pe(b) + n <- nrow(ins) + expect_equal(r$coefficients["smoker", "RESI"], + t2S(s$p.table["smoker", "t value"], b$df.residual, n)) + expect_equal(r$anova["s(age)", "RESI"], + f2S(s$s.table["s(age)", "F"], s$s.table["s(age)", "Ref.df"], + b$df.residual, n)) + expect_equal(r$anova["region", "RESI"], + f2S(s$pTerms.table["region", "F"], 3, b$df.residual, n)) + + bb <- mgcv::gam(I(charges > 15000) ~ smoker + s(age), family = binomial, + data = ins) + sb <- mgcv::summary.gam(bb) + rb <- resi_pe(bb) + expect_equal(rb$anova["s(age)", "RESI"], + chisq2S(sb$s.table["s(age)", "Chi.sq"], + sb$s.table["s(age)", "Ref.df"], n)) + expect_true("z value" %in% colnames(rb$coefficients)) +}) + +test_that("resi_pe.gam returns NA for smooths without a null space", { + skip_if_not_installed("mgcv") + ins <- RESI::insurance + ins$region <- factor(ins$region) + b <- mgcv::bam(log10(charges) ~ smoker + s(age) + s(region, bs = "re"), + data = ins) + expect_warning(r <- resi_pe(b), "null space") + expect_true(is.na(r$anova["s(region)", "RESI"])) + expect_false(is.na(r$anova["s(age)", "RESI"])) + expect_error(resi(b), "resi_pe") +})