R/semireg-methods.R

Defines functions tidy.semireg VarCorr.semireg ranef.semireg fixef.semireg family.semireg formula.semireg nobs.semireg logLik.semireg residuals.semireg predict.semireg fitted.semireg vcov.semireg coef.semireg print.summary.semireg summary.semireg pm_sr_other_vc pm_sr_print_smooths print.semireg pm_sr_smooth_table

Documented in predict.semireg

## A semireg fit as a model: a short print, a table of the smooth terms, and
## the usual extractors, all from the fitted mixed model ('semer'), so code
## written for lmer/glmmTMB fits works on a semireg fit too.

## The smooth terms of a fit, one row per random-effect block: the smooth as
## written (label), its random-effect term, basis, number of basis functions,
## dimension of the basis (columns of its random-effect design), smoothing
## variance (on the scale of the fit) and whether it is estimated as a straight
## line (variance 0).
pm_sr_smooth_table <- function(fit) {
  sm <- fit$smooths
  blocks <- names(sm$maps)
  if (!length(blocks)) return(NULL)
  v <- pm_sr_block_vars(fit)
  # each block's own smooth (a t2(), lvis or pspline2d smooth has several blocks)
  sm_of <- function(b) sm$sms[[sm$maps[[b]][[1]]$sm]]
  bas <- vapply(blocks, function(b) {
    s <- sm_of(b)
    if (!is.null(s$pm_basis)) return(if (s$pm_basis$preset == "lvis") "lvis" else "pspline2d")
    sub("\\.smooth.spec$|\\.smooth$", "", class(s)[1])
  }, "", USE.NAMES = FALSE)
  # (an lvis or pspline2d component: its own columns, not the whole basis)
  dim <- vapply(blocks, function(b) {
    s <- sm_of(b)
    if (!is.null(s$pm_basis)) return(as.numeric(ncol(sm$maps[[b]][[1]]$A)))
    if (is.null(s$bs.dim)) NA_real_ else as.numeric(s$bs.dim)
  }, numeric(1), USE.NAMES = FALSE)
  var <- if (is.null(v)) rep(NA_real_, length(blocks)) else unname(v[blocks])
  flat <- !is.na(var) & var < 1e-8 * max(1, abs(var), na.rm = TRUE)
  # the covariates of each block: what semipred(covariate = ) takes, and what
  # sm_term = "<covariate>" selects (every smooth of that covariate)
  covs <- vapply(blocks, function(b) {
    s <- sm$sms[vapply(sm$maps[[b]], `[[`, 1L, "sm")]
    paste(unique(unlist(lapply(s, `[[`, "term"))), collapse = ", ")
  }, "")
  # the label(s) of each block's smooths (a t2() or by-factor smooth: several blocks)
  labs <- vapply(blocks, function(b) {
    l <- unique(vapply(sm$maps[[b]], function(m) sm$sms[[m$sm]]$label, ""))
    if (length(l) > 3) paste(c(l[1:2], "..."), collapse = ", ") else paste(l, collapse = ", ")
  }, "")
  out <- data.frame(smooth = unname(labs), term = blocks,
                    covariate = unname(covs), basis = bas, basis_dim = dim, variance = var, linear = flat, row.names = NULL)
  # terms fitted as another (te() as t2(); K): the term as written and the call
  # fitted, one row per term, as an attribute (the table keeps one layout)
  rq <- unique(do.call(rbind, lapply(sm$sms, function(s) if (!is.null(s$pm_requested))
    data.frame(requested = s$pm_requested, fitted = s$pm_fitted, stringsAsFactors = FALSE))))
  if (!is.null(rq) && nrow(rq)) attr(out, "requested") <- `rownames<-`(rq, NULL)
  out
}

#' @exportS3Method print semireg
print.semireg <- function(x, ...) {
  m <- x$semer
  tmb <- inherits(m, "glmmTMB")
  fam <- tryCatch(stats::family(m), error = function(e) NULL)
  cat("Semiparametric ", if (tmb) "glmmTMB" else if (inherits(m, "glmerMod")) "glmer" else "lmer", " fit",
      if (!is.null(fam)) paste0(" (", fam$family, ", ", fam$link, ")"),
      if (isTRUE(tryCatch(lme4::isREML(m), error = function(e) tmb && isTRUE(m$modelInfo$REML)))) ", REML" else "",
      "\n", sep = "")
  cat("Formula: ", paste(trimws(deparse(stats::formula(x))), collapse = " "), "\n", sep = "")
  ll <- tryCatch(stats::logLik(m), error = function(e) NULL)
  cat("Observations: ", stats::nobs(m), if (!is.null(ll)) paste0("; logLik ", format(signif(as.numeric(ll), 6)),
      ", AIC ", format(signif(stats::AIC(m), 6))), "\n", sep = "")
  st <- pm_sr_smooth_table(x)
  if (!is.null(st)) {
    cat("\nSmooth terms (variance of each smooth's random effects):\n")
    pm_sr_print_smooths(st)
  }
  cat("\nFixed effects:\n")
  print(signif(pm_coef(m), 5))
  vc <- tryCatch(pm_sr_other_vc(x), error = function(e) NULL)
  if (!is.null(vc) && nrow(vc)) {
    cat("\nOther variance components:\n")
    print(vc, row.names = FALSE)
  }
  pm_print_advice(x)
  invisible(x)
}

## The smooth table as printed, with a line on how semipred() selects them.
pm_sr_print_smooths <- function(st) {
  p <- st[c("smooth", "term", "covariate", "basis", "basis_dim", "variance", "linear")]
  p$variance <- signif(p$variance, 4)
  p$linear <- ifelse(p$linear, "yes", "")
  print(p, row.names = FALSE)
  rq <- attr(st, "requested")                   # (te() fitted as t2(): the term as written; K)
  if (!is.null(rq)) cat(paste0(rq$requested, " was fitted as ", rq$fitted, " (penalties as random effects)."), sep = "\n")
  ex <- st$smooth[1]
  cat(strwrap(paste0("semipred(): covariate = a 'covariate' above; sm_term = a 'smooth' or 'term' (e.g. \"", ex,
                      "\"), or a covariate for all its smooths; default every smooth."), width = 0.95 * getOption("width")),
      sep = "\n")
}

## Variance components other than the smooths (random effects of the formula,
## residual), as a small table.
pm_sr_other_vc <- function(x) {
  m <- x$semer
  blocks <- names(x$smooths$maps)
  if (inherits(m, "glmmTMB")) {
    vc <- glmmTMB::VarCorr(m)$cond
    d <- data.frame(group = names(vc), variance = vapply(vc, function(v) as.matrix(v)[1, 1], numeric(1)))
    s <- stats::sigma(m)
    fam <- stats::family(m)$family
    if (fam %in% c("gaussian")) d <- rbind(d, data.frame(group = "Residual", variance = s^2))
  } else {
    v <- as.data.frame(lme4::VarCorr(m))
    v <- v[is.na(v$var2), ]
    d <- data.frame(group = ifelse(v$var1 %in% c(NA, "(Intercept)"), v$grp, paste(v$grp, v$var1)), variance = v$vcov)
    d <- d[!(v$grp %in% blocks), , drop = FALSE]
  }
  d <- d[!(d$group %in% blocks), , drop = FALSE]
  d$variance <- signif(d$variance, 4)
  d
}

## summary(): the summary of the fitted model with the smooth table.
#' @exportS3Method summary semireg
summary.semireg <- function(object, ...) {
  structure(list(model = summary(object$semer, ...), smooths = pm_sr_smooth_table(object),
                 advice = pm_advice_get(object)), class = "summary.semireg")
}

#' @exportS3Method print summary.semireg
print.summary.semireg <- function(x, ...) {
  print(x$model, ...)
  if (!is.null(x$smooths)) {
    cat("\nSmooth terms:\n")
    pm_sr_print_smooths(x$smooths)
  }
  if (!is.null(x$advice)) cat(pm_format_advice(x$advice))
  invisible(x)
}

## Extractors: those of the fitted mixed model.
#' @exportS3Method stats::coef semireg
coef.semireg <- function(object, ...) pm_coef(object$semer)
#' @exportS3Method stats::vcov semireg
vcov.semireg <- function(object, ...) pm_vcov(object$semer)
#' @exportS3Method stats::fitted semireg
fitted.semireg <- function(object, ...) stats::fitted(object$semer, ...)
#' Predictions from a semireg fit
#'
#' Population predictions of a \code{semireg()} or \code{semireg_tmb()} fit at new data: the fixed effects and
#' the smooth terms, with the other random effects (and random curves \code{s(x) | g}) at zero. For the fitted
#' values with every random effect, use \code{fitted()}.
#'
#' \code{semipred()} answers another question: curves on a reference grid, averaged over the factors not in
#' \code{modelterm}, with other covariates at reference values. \code{predict()} gives one value per row of
#' \code{newdata}, from that row's own values; averaged over the same grid it gives \code{semipred()}'s means.
#'
#' The design is that of \code{semipred()} (\code{mgcv::PredictMat()} of the stored smooths, then the map to the
#' fit's random-effect columns), so \code{predict()} at the points of a \code{semipred()} grid gives its estimates
#' and SEs. Offsets written in the formula (\code{offset(o)}) are taken from \code{newdata}; an offset given as
#' the \code{offset} argument of the fit is not (as \code{predict.gam()}).
#' @param object A \code{semireg()} or \code{semireg_tmb()} fit.
#' @param newdata A data frame with the variables of the fixed part and of the smooths; default: the data of
#'   the fit.
#' @param type \code{"link"} (the linear predictor), \code{"response"} (the inverse link of it; an identity
#'   link gives the same), or \code{"lpmatrix"}: the (sparse) matrix \code{[X, Z]} whose product with
#'   \code{attr(, "coef")} (fixed effects, then the predicted smooth coefficients; \code{as.numeric()} of the
#'   product) is the linear predictor
#'   without the offset (\code{attr(, "offset")}).
#' @param se.fit Return standard errors as well (a list with \code{fit} and \code{se.fit}). On the response
#'   scale by the delta method.
#' @param unconditional Include the uncertainty of the smoothing parameters (the first-order correction of
#'   \code{semipred()}). \code{NULL}: as \code{semipred()}, with the correction for generalized fits only.
#' @param sm_term The smooth blocks to include (default all; names as in \code{print(fit)}).
#' @param ... Not used.
#' @return A vector of predictions, a list with \code{fit} and \code{se.fit}, or the \code{"lpmatrix"}.
#'   The attribute \code{"unconditional"} says whether the correction was used.
#' @examples
#' set.seed(1)
#' d <- data.frame(x = runif(100), g = gl(10, 10))
#' d$y <- sin(2 * pi * d$x) + rnorm(10, sd = 0.3)[d$g] + rnorm(100, sd = 0.3)
#' fit <- semireg(y ~ s(x) + (1 | g), data = d)
#' predict(fit, data.frame(x = c(0.25, 0.5)), se.fit = TRUE)
#' @exportS3Method stats::predict semireg
predict.semireg <- function(object, newdata = NULL, type = c("link", "response", "lpmatrix"), se.fit = FALSE,
                            unconditional = NULL, sm_term = NULL, ...) {
  type <- match.arg(type)
  semer <- object$semer
  if (is.null(object$u_lst) || is.null(object$CovMat))
    stop("This fit has no prediction information (made before predictmeans 2.0): refit it with semireg().",
         call. = FALSE)
  if (is.null(object$smooths))
    stop("This fit has its smooths in 'smoothZ' (smZ(), before 2.0): refit it with the smooths in the formula.",
         call. = FALSE)
  if (is.null(newdata)) newdata <- object$data
  newdata <- as.data.frame(newdata)
  blk <- intersect(names(object$u_lst), names(object$smooths$maps))
  if (is.null(sm_term)) sm_term <- blk
  bad <- setdiff(sm_term, blk)
  if (length(bad)) stop("'sm_term' must be among the smooth blocks: ", paste(blk, collapse = ", "), call. = FALSE)
  blocks <- blk[blk %in% sm_term]
  # the fixed part: the basis Kmatrix() uses (pm_grid_basis(), R/Kmatrix.R),
  # factor levels and contrasts of the fit, columns of the fit (aliased dropped)
  info <- pm_model_info(object)
  rec <- pm_recover_data(info)
  basis <- pm_grid_basis(info, rec$data, list())
  beta <- pm_coef(semer)
  X <- basis$fun(newdata)
  miss <- setdiff(names(beta), colnames(X))
  if (length(miss)) stop("The new data do not give the fixed-effect column(s) ", paste(miss, collapse = ", "), ".",
                         call. = FALSE)
  X <- X[, names(beta), drop = FALSE]
  off <- stats::model.offset(stats::model.frame(basis$Terms, newdata, na.action = stats::na.pass))
  if (is.null(off)) off <- rep(0, nrow(X))
  # the smooths on the rows with all their covariates (NA rows give NA, as
  # predict.gam(); PredictMat() stops on NA); the design kept sparse (n x q)
  X <- Matrix::Matrix(X, sparse = TRUE)
  D <- X
  if (length(blocks)) {
    sv <- intersect(object$sm_vars, names(newdata))
    ok <- stats::complete.cases(newdata[sv])
    Z <- if (all(ok)) do.call(cbind, pm_sm_predict(object$smooths, newdata, blocks)) else {
      Zo <- Matrix::Matrix(NA_real_, nrow(newdata), sum(vapply(object$u_lst[blocks], length, 0L)))
      if (any(ok)) Zo[ok, ] <- as.matrix(do.call(cbind, pm_sm_predict(object$smooths, newdata[ok, , drop = FALSE],
                                                                      blocks)))
      Zo
    }
    D <- cbind(X, Z)
  }
  b <- c(beta, unlist(unname(object$u_lst[blocks])))
  if (type == "lpmatrix") return(structure(D, coef = b, offset = off))
  eta <- as.numeric(D %*% b) + off
  cc <- pm_sr_coef_cov(object, blocks, unconditional, cov = se.fit)
  if (type == "response" && inherits(semer, "glmmTMB") && !is.null(pm_zi_component(semer)))
    stop("type = \"response\" of a zero-inflated fit: predict() gives the count part only (not the zero ",
         "inflation); use type = \"link\", or predictmeans(type = \"response\") for overall means.", call. = FALSE)
  # (the link decides, not the family: gaussian(link = "log") of semireg_tmb() has one)
  fam <- tryCatch(stats::family(semer), error = function(e) NULL)
  if (type == "response" && !is.null(fam) && !identical(fam$link, "identity")) {
    fit <- fam$linkinv(eta)
    d_mu <- abs(fam$mu.eta(eta))
  } else {
    fit <- eta
    d_mu <- 1
  }
  names(fit) <- rownames(newdata)
  if (!se.fit) return(structure(fit, unconditional = cc$unc[["used"]]))
  se <- stats::sigma(semer) * sqrt(Matrix::rowSums((D %*% as.matrix(cc$V)) * D)) * d_mu
  names(se) <- names(fit)
  structure(list(fit = fit, se.fit = se), unconditional = cc$unc[["used"]])
}
#' @exportS3Method stats::residuals semireg
residuals.semireg <- function(object, ...) stats::residuals(object$semer, ...)
#' @exportS3Method stats::logLik semireg
logLik.semireg <- function(object, ...) stats::logLik(object$semer, ...)
#' @exportS3Method stats::nobs semireg
nobs.semireg <- function(object, ...) stats::nobs(object$semer, ...)
## The formula as written (with s() terms); the expanded formula that was
## fitted is x$refit$formula.
#' @exportS3Method stats::formula semireg
formula.semireg <- function(x, ...) {
  f <- x$call$formula
  if (is.null(f)) return(x$refit$formula)
  f <- eval(f, environment(x$refit$formula))
  if (inherits(f, "formula")) f else stats::as.formula(f)
}
#' @exportS3Method stats::family semireg
family.semireg <- function(object, ...) stats::family(object$semer, ...)
#' @exportS3Method nlme::fixef semireg
fixef.semireg <- function(object, ...) pm_coef(object$semer)
#' @exportS3Method nlme::ranef semireg
ranef.semireg <- function(object, ...) nlme::ranef(object$semer, ...)
#' @exportS3Method nlme::VarCorr semireg
VarCorr.semireg <- function(x, sigma = 1, ...) {
  if (inherits(x$semer, "glmmTMB")) glmmTMB::VarCorr(x$semer, ...) else lme4::VarCorr(x$semer, ...)
}

## tidy(): one table of the smooth terms (as print shows); tidy(fit, "fixed")
## the fixed effects with SEs.
#' @exportS3Method generics::tidy semireg
tidy.semireg <- function(x, what = c("smooths", "fixed"), ...) {
  what <- match.arg(what)
  if (what == "smooths") return(pm_sr_smooth_table(x))
  b <- pm_coef(x$semer)
  se <- sqrt(diag(pm_vcov(x$semer)))[names(b)]
  data.frame(term = names(b), estimate = unname(b), std.error = unname(se), statistic = unname(b / se), row.names = NULL)
}

Try the predictmeans package in your browser

Any scripts or data that you put into this service are public.

predictmeans documentation built on Dec. 3, 2026, 5:07 p.m.