R/helpers_qic.R

Defines functions compare_gee_corstr

compare_gee_corstr <- function(data,
                               formula = NULL,
                               criterion = c('QIC', 'CIC', 'QICC'),
                               tolerance = 1e-8,
                               factors = 'trat') {

  criterion <- match.arg(criterion)

  corstrs <- c(
    'independence',
    'exchangeable',
    'ar1',
    'unstructured'
  )

  gee_data <- prepare_gee_data(
    data,
    factors = factors
  )

  if (is.null(formula)) {
    formula <- build_factorial_formula(
      factors = factors,
      response = 'DI_ang',
      time = 'time',
      include_factorial_time = TRUE
    )
  }

  results <- lapply(corstrs, function(cs) {

    tryCatch({

      fit <- geepack::geeglm(
        formula = formula,
        id = .parcela_id,
        data = gee_data,
        corstr = cs,
        family = stats::gaussian()
      )

      # Mantém os dados disponíveis para geepack::QIC()
      fit$call$data <- gee_data

      q <- geepack::QIC(fit)

      list(
        row = data.frame(
          corstr = cs,
          QIC = unname(q['QIC']),
          QICu = unname(q['QICu']),
          CIC = unname(q['CIC']),
          QICC = unname(q['QICC']),
          converged = TRUE,
          error = NA_character_,
          stringsAsFactors = FALSE
        ),
        fit = fit
      )

    }, error = function(e) {

      list(
        row = data.frame(
          corstr = cs,
          QIC = NA_real_,
          QICu = NA_real_,
          CIC = NA_real_,
          QICC = NA_real_,
          converged = FALSE,
          error = conditionMessage(e),
          stringsAsFactors = FALSE
        ),
        fit = NULL
      )
    })
  })

  tab <- do.call(rbind, lapply(results, `[[`, 'row'))
  fits <- lapply(results, `[[`, 'fit')
  names(fits) <- corstrs

  tab$selected <- FALSE

  valid <- tab$converged & is.finite(tab[[criterion]])

  if (any(valid)) {
    best <- min(tab[[criterion]][valid])

    tab$selected[valid] <-
      abs(tab[[criterion]][valid] - best) <= tolerance
  }

  tab <- tab[order(tab[[criterion]], na.last = TRUE), ]
  rownames(tab) <- NULL

  list(
    comparison = tab,
    fits = fits,
    criterion = criterion,
    tolerance = tolerance,
    formula = formula,
    factors = factors
  )
}

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.