R/methods.R

Defines functions check_dots print.summary.ijse print.ijse summary.ijse confint.ijse influence.ijse vcov.ijse coef.ijse

Documented in coef.ijse confint.ijse influence.ijse print.ijse print.summary.ijse summary.ijse vcov.ijse

#' Summarize IJ inference
#'
#' Standard methods for posterior expectations and their IJ sampling covariance.
#' Normal intervals are centered on posterior expectations and use IJ SEs; they
#' are not posterior credible intervals or a small-cluster correction.
#'
#' @param object,x,model An \code{ijse} object, or its summary for the summary print method.
#' @param parm Parameter names or integer indices; defaults to all quantities.
#' @param level Confidence level strictly between zero and one.
#' @param digits Number of significant digits used for printing.
#' @param type For \code{vcov()}, select IJ sampling covariance (default) or
#'   covariance of the posterior draws with \code{type = "posterior"}.
#' @param ... Reserved for future arguments; must be empty.
#' @details \code{confint()} uses the posterior expectation plus or minus
#'   a standard-normal critical value times the IJ SE. It is symmetric and
#'   uses a normal reference, even for clustered results. It is not an equal-tailed
#'   posterior credible interval, an IJ Monte Carlo interval, or a t correction.
#'   The upper-tail calculation avoids rounding a valid probability to one when
#'   \code{level} is very close to one. Below \code{level = 1e-8}, the central
#'   inverse-probability expansion \eqn{\sqrt{\pi/2}\,level} avoids losing a tiny
#'   positive level; its omitted relative correction is below double precision.
#'   Floating-point precision can limit display
#'   of extreme confidence levels and very narrow interval endpoints.
#'
#'   \code{SE_ratio} in the summary is \code{IJ_SE / Posterior_SD}; it is
#'   \code{NA} when the posterior SD is zero. A larger ratio alone does not prove
#'   calibrated inference. The two \code{vcov()} choices estimate distinct objects.
#'   Posterior covariance is unavailable in objects saved before version 0.3.0;
#'   recompute those objects to request it.
#'
#'   Saved \code{influence()} values are \eqn{K\widehat C_u}, not zero-centered
#'   influence values. Divide by \code{n_units} to obtain case-weight derivative
#'   estimates. For a small likelihood-weight change \eqn{\Delta w_u},
#'   \eqn{\Delta E(g\mid y)\approx\widehat C_u\Delta w_u}; downweighting reverses
#'   the derivative's sign. Deleting a whole unit is a finite perturbation and
#'   need not equal this local approximation. The rows need not have mean zero.
#'   Sampling covariance centers across units, so
#'   \code{cov(t(influence(result))) / result$n_units} reproduces \code{vcov(result)}.
#'   Use \code{result$unit_ids} for exact cluster IDs; columns use unique display
#'   labels. Independent observations use their likelihood-column indices.
#'
#'   In a finite-draw importance-reweighting check, normalized empirical weights
#'   differentiate with denominator \eqn{S}, whereas IJSE uses sample covariance
#'   with denominator \eqn{S-1}. Multiply that numerical derivative by
#'   \eqn{S/(S-1)} when checking equality. This is a testing identity, not an extra
#'   correction to apply to the reported IJ SE.
#'
#' @return \code{coef()} returns a named vector of posterior expectations.
#'   \code{vcov()} returns the \eqn{P\times P} IJ sampling covariance by default,
#'   or posterior draw covariance for \code{type = "posterior"}.
#'   \code{confint()} returns a quantities-by-two matrix, in the requested
#'   \code{parm} order, with percentage-labeled columns. When the percentage
#'   labels would coincide at display precision, columns are named \code{lower}
#'   and \code{upper}.
#'   \code{influence()} returns the saved quantities-by-units matrix or errors
#'   when influence was not retained.
#'   \code{summary()} returns a \code{summary.ijse} list: \code{coefficients}
#'   (Estimate, Posterior_SD, IJ_SE, SE_ratio, lower and upper limits), counts,
#'   \code{clustered}, \code{unit_ids}, \code{level}, \code{diagnostics} and \code{call}.
#'   Print methods invisibly return their input.
#' @seealso \code{\link{ijse_draws}}, \code{\link{ijse}}.
#' @name summary.ijse
#' @importFrom stats coef confint vcov influence
#' @examples
#' set.seed(1)
#' y <- c(-1, 0, 0.5, 1, 2)
#' v <- 1 / (length(y) + 1 / 4)
#' d <- cbind(theta = rnorm(1000, v * sum(y), sqrt(v)))
#' ll <- vapply(y, function(yi) dnorm(yi, d[, 1], log = TRUE),
#'              numeric(nrow(d)))
#' result <- ijse_draws(d, ll, save_influence = TRUE)
#' coef(result)
#' vcov(result)
#' confint(result, level = 0.90)
#' summary(result)
#' vcov(result, type = "posterior")
#' influence(result) / result$n_units
#' stopifnot(isTRUE(all.equal(
#'   cov(t(influence(result))) / result$n_units, vcov(result))))
NULL

#' @rdname summary.ijse
#' @export
coef.ijse <- function(object, ...) {
  check_dots(...)
  object$estimate
}

#' @rdname summary.ijse
#' @export
vcov.ijse <- function(object, ..., type = c("ij", "posterior")) {
  check_dots(...)
  type <- match.arg(type)
  if (type == "posterior" && is.null(object$posterior_vcov)) {
    stop("Posterior covariance is unavailable in this result. Recompute with IJSE >= 0.3.0.", call. = FALSE)
  }
  if (type == "ij") object$vcov else object$posterior_vcov
}

#' @rdname summary.ijse
#' @export
influence.ijse <- function(model, ...) {
  check_dots(...)
  if (is.null(model$influence)) {
    stop("Influence was not retained. Recompute with 'save_influence = TRUE'.", call. = FALSE)
  }
  model$influence
}

#' @rdname summary.ijse
#' @export
confint.ijse <- function(object, parm, level = 0.95, ...) {
  check_dots(...)
  if (!is.numeric(level) || is.complex(level) || length(level) != 1L ||
      !is.finite(level) || level <= 0 || level >= 1) {
    stop("'level' must be a number strictly between zero and one.", call. = FALSE)
  }
  nm <- names(object$estimate)
  if (missing(parm)) parm <- nm
  if (is.numeric(parm) && !is.complex(parm)) {
    if (!length(parm) || anyNA(parm) || any(!is.finite(parm)) ||
        any(parm != floor(parm)) || any(parm < 1L | parm > length(nm)) ||
        anyDuplicated(parm)) {
      stop("'parm' must contain valid, unique parameter indices.", call. = FALSE)
    }
    parm <- nm[parm]
  }
  parm <- select_names(parm, nm, "parm")
  prob <- c((1 - level) / 2, (1 + level) / 2)
  # For a valid level very close to one, (1 + level) / 2 can round to 1.
  # Evaluate the upper-tail quantile from the accurately retained lower tail.
  critical <- if (level < 1e-8) {
    # The inverse central probability is sqrt(pi/2)*level + O(level^3).
    # Here its relative correction is below double precision, while forming
    # (1-level)/2 can erase a tiny positive level altogether.
    sqrt(pi / 2) * level
  } else stats::qnorm((1 - level) / 2, lower.tail = FALSE)
  out <- outer(object$se[parm], c(-critical, critical)) + object$estimate[parm]
  labels <- paste0(format(100 * prob, trim = TRUE), " %")
  if (anyDuplicated(labels)) labels <- c("lower", "upper")
  dimnames(out) <- list(parm, labels)
  out
}

#' @rdname summary.ijse
#' @export
summary.ijse <- function(object, level = 0.95, ...) {
  check_dots(...)
  interval <- stats::confint(object, level = level)
  ratio <- object$se / object$posterior_sd
  ratio[object$posterior_sd == 0] <- NA_real_
  table <- cbind(Estimate = object$estimate, Posterior_SD = object$posterior_sd,
                 IJ_SE = object$se, SE_ratio = ratio, interval)
  structure(list(coefficients = table, n_obs = object$n_obs,
                 n_units = object$n_units, n_draws = object$n_draws,
                 clustered = object$clustered, unit_ids = object$unit_ids, level = level,
                 diagnostics = object$diagnostics, call = object$call),
            class = "summary.ijse")
}

#' @rdname summary.ijse
#' @export
print.ijse <- function(x, digits = max(3L, getOption("digits") - 3L), ...) {
  check_dots(...)
  print(summary(x), digits = digits)
  invisible(x)
}

#' @rdname summary.ijse
#' @export
print.summary.ijse <- function(x, digits = max(3L, getOption("digits") - 3L), ...) {
  check_dots(...)
  cat("Infinitesimal jackknife inference\n")
  cat(x$n_draws, "posterior draws;", x$n_obs, "observations;", x$n_units,
      if (x$clustered) "clusters\n\n" else "independent units\n\n")
  print(x$coefficients, digits = digits)
  cat("\nIntervals:", format(100 * x$level),
      "% normal approximation for posterior expectations.\n", sep = " ")
  if (!is.null(x$diagnostics$chain_relative_range)) {
    cat("Chain IJ SE relative ranges (stability checks):\n")
    print(x$diagnostics$chain_relative_range, digits = digits)
  }
  invisible(x)
}

check_dots <- function(...) {
  if (length(list(...))) stop("Unused arguments in '...'.", call. = FALSE)
}

Try the IJSE package in your browser

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

IJSE documentation built on Oct. 22, 2026, 5:18 p.m.