R/helpers_wald.R

Defines functions safe_anova wald_interaction

wald_interaction <- function(model, factors = 'trat', time = 'time') {

  beta <- stats::coef(model)
  V <- stats::vcov(model)
  nomes <- names(beta)

  factors <- unique(as.character(factors))

  # Identifica, pela matriz do modelo, quais coeficientes pertencem
  # a termos que envolvem simultaneamente tempo e fator(es) de tratamento.
  tt <- stats::terms(model)
  term_labels <- attr(tt, 'term.labels')

  temporal_terms <- vapply(
    strsplit(term_labels, ':', fixed = TRUE),
    function(parts) {
      time %in% parts && any(factors %in% parts)
    },
    logical(1)
  )

  target_terms <- which(temporal_terms)

  if (length(target_terms) == 0L) {
    stop(
      'The model has no treatment-factor-by-time interactions.',
      call. = FALSE
    )
  }

  X <- stats::model.matrix(model)
  assign <- attr(X, 'assign')

  coef_idx <- which(assign %in% target_terms)
  coef_names <- colnames(X)[coef_idx]
  idx <- match(coef_names, nomes, nomatch = 0L)
  idx <- idx[idx > 0L]

  if (length(idx) == 0L) {
    stop(
      'No estimable coefficients were found for the time interactions.',
      call. = FALSE
    )
  }

  b <- beta[idx]
  Vb <- V[idx, idx, drop = FALSE]
  df <- length(b)

  # Um Wald conjunto requer coeficientes e covariancias finitos.
  if (any(!is.finite(b)) || any(!is.finite(Vb))) {
    return(data.frame(
      test = 'Wald',
      term = 'interaction',
      statistic = NA_real_,
      df = df,
      p.value = NA_real_,
      reason = 'non-finite coefficients or covariance matrix',
      row.names = NULL
    ))
  }

  # Detecta dispersao praticamente nula em relacao a variabilidade
  # observada da resposta. Nessa situacao, a matriz de covariancia
  # pode ser formalmente inversivel, mas o Wald torna-se numericamente
  # nao confiavel.
  response <- stats::model.response(stats::model.frame(model))
  response_var <- stats::var(response, na.rm = TRUE)

  dispersion <- tryCatch(
    as.numeric(model$geese$gamma[1L]),
    error = function(e) NA_real_
  )

  dispersion_ratio <- if (
    is.finite(dispersion) &&
    is.finite(response_var) &&
    response_var > 0
  ) {
    dispersion / response_var
  } else {
    NA_real_
  }

  if (
    is.finite(dispersion_ratio) &&
    dispersion_ratio <= sqrt(.Machine$double.eps)
  ) {
    return(data.frame(
      test = 'Wald',
      term = 'interaction',
      statistic = NA_real_,
      df = df,
      p.value = NA_real_,
      reason = 'near-zero model dispersion',
      row.names = NULL
    ))
  }

  # Nao usar pseudoinversa silenciosamente: se Vb nao puder ser
  # resolvida de forma numericamente confiavel, o teste e reportado
  # como nao calculavel.
  solved <- tryCatch(
    solve(Vb, b),
    error = function(e) NULL
  )

  if (is.null(solved) || any(!is.finite(solved))) {
    return(data.frame(
      test = 'Wald',
      term = 'interaction',
      statistic = NA_real_,
      df = df,
      p.value = NA_real_,
      reason = 'singular covariance matrix',
      row.names = NULL
    ))
  }

  W <- as.numeric(t(b) %*% solved)

  if (!is.finite(W) || W < 0) {
    return(data.frame(
      test = 'Wald',
      term = 'interaction',
      statistic = NA_real_,
      df = df,
      p.value = NA_real_,
      reason = 'invalid Wald statistic',
      row.names = NULL
    ))
  }

  p <- stats::pchisq(
    W,
    df = df,
    lower.tail = FALSE
  )

  data.frame(
    test = 'Wald',
    term = 'interaction',
    statistic = W,
    df = df,
    p.value = p,
    reason = NA_character_,
    row.names = NULL
  )
}

safe_anova <- function(model0, model1, test = 'Wald',
                       factors = 'trat', time = 'time') {

  resultado <- tryCatch(
    stats::anova(model0, model1, test = test),
    error = function(e) NULL
  )

  if (!is.null(resultado)) {
    return(resultado)
  }

  message(
    'anova() failed; using a manual Wald test for time interactions.'
  )

  wald_interaction(
    model1,
    factors = factors,
    time = time
  )
}

Try the infectionIndex package in your browser

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

infectionIndex documentation built on Dec. 4, 2026, 5:10 p.m.