R/methods_survival.R

Defines functions sanitize_model_specific.coxph get_predict.coxph set_coef.survreg

Documented in get_predict.coxph sanitize_model_specific.coxph set_coef.survreg

#' @include set_coef.R
#' @rdname set_coef
#' @export
set_coef.survreg <- function(model, coefs, ...) {
    # `coefs` holds the regression coefficients first, followed by one
    # `Log(scale)` entry per stratum (`insight::get_parameters.survreg()` builds
    # it from `summary.survreg()`). Peel the scale entries off the tail: indexing
    # by `nvar0` dropped a regression coefficient and read the scale from the
    # wrong slot.

    nvar0 <- length(model$coefficients)
    nvar <- nrow(model$var)
    if (nvar > nvar0) {
        model[["coefficients"]][] <- coefs[seq_len(nvar0)]
        model[["scale"]][] <- exp(coefs[(nvar0 + 1):nvar])
    } else {
        model$coefficients[] <- coefs
    }

    model
}

#' @rdname get_predict
#' @export
get_predict.coxph <- function(
    model,
    newdata = get_modeldata(model),
    type = "lp",
    ...) {
    out <- stats::predict(model, newdata = newdata, type = type, ...)
    out <- data.table(estimate = out)
    out <- add_rowid(out, newdata)
    return(out)
}


#' @rdname sanitize_model_specific
#' @export
sanitize_model_specific.coxph <- function(model, vcov, ...) {
    insight::check_if_installed("survival")
    flag1 <- !isFALSE(vcov)
    flag2 <- !isTRUE(checkmate::check_choice(vcov, choices = c("rsample", "boot", "fwb")))
    flag3 <- isTRUE(getOption("marginaleffects_safe", default = TRUE))
    if (flag1 && flag2 && flag3) {
        msg <- 'The default delta method standard errors for `coxph` models only take into account uncertainty in the regression coefficients. Standard errors may be too small. Use the `inferences()` function or set `vcov` to "rsample", "boot"  or "fwb" to compute confidence intervals by bootstrapping. Set `vcov` to `FALSE` or `options(marginaleffects_safe=FALSE)` to silence this warning.'
        warning(msg, call. = FALSE)
    }
    return(model)
}

Try the marginaleffects package in your browser

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

marginaleffects documentation built on Sept. 3, 2026, 9:08 a.m.