Nothing
#' Methods for fitted generalized competing event models
#'
#' @description
#' Methods for objects of class \code{"gcemod"} returned by
#' \code{\link{gcecox}}, \code{\link{gcefg}}, and \code{\link{gcecif}}, and for
#' the \code{"gce_lunnmcneil"} objects returned by \code{\link{lunnmcneil}}.
#'
#' @details
#' The fitting functions return objects of class \code{c("gcecox", "gcemod")},
#' \code{c("gcefg", "gcemod")}, and \code{c("gcecif", "gcemod")}. Behaviour
#' common to the three models is implemented in the methods for the parent
#' class \code{"gcemod"}. Where a model needs its own behaviour
#' (\code{summary}, \code{predict}, \code{logLik}, \code{plot}), a method for
#' the specific class supplies it and calls the parent method through
#' \code{\link[base]{NextMethod}} for the common part.
#'
#' \describe{
#' \item{\code{print}}{a short display: the call, the sample and event
#' counts, and the estimated ratios \code{exp(coef)}.}
#' \item{\code{summary}}{returns an object of class \code{"summary.gcemod"}
#' (or \code{"summary.gce_lunnmcneil"}) holding the full coefficient table
#' (estimate, ratio, standard error, Wald \eqn{z}, p-value), the
#' confidence intervals for the ratios, the omnibus Wald test, and the
#' baseline quantity of the model (\eqn{\omega^{+}(t)} of the average
#' subject, or \eqn{F_1(t)}, \eqn{F_2(t)}, and \eqn{\rho(t)}). Its
#' \code{print} method formats the table with
#' \code{\link[stats]{printCoefmat}}. \code{coef()} applied to the
#' summary object returns the coefficient table.}
#' \item{\code{coef}, \code{vcov}, \code{confint}}{the log ratios (log
#' \eqn{\omega^{+}} ratios; log \eqn{\rho} ratios for \code{gcecif}), their
#' covariance matrix, and Wald confidence intervals, all on the reported
#' coefficient scale (per unit, or per SD if the model was fitted with
#' \code{standardize = TRUE}). \code{confint(exponentiate = TRUE)} returns
#' intervals for the ratios.}
#' \item{\code{logLik}}{the maximized log partial likelihood of the stacked
#' model for \code{gcecox} fits, and the corresponding weighted log
#' partial pseudo-likelihood for \code{gcefg} fits (useful for comparing
#' nested specifications descriptively; it is not a genuine likelihood).
#' \code{gcecif} is estimated by generalized estimating equations and has
#' no likelihood, so \code{logLik} signals an error.}
#' \item{\code{nobs}, \code{formula}, \code{terms}, \code{model.frame},
#' \code{model.matrix}}{the number of subjects and the stored model
#' specification. \code{update()} works through the stored call.}
#' \item{\code{predict}, \code{fitted}}{see below.}
#' \item{\code{plot}}{dispatches to the display functions; see \code{which}.}
#' }
#'
#' @section Prediction:
#' \code{predict()} rebuilds the design matrix for \code{newdata} from the
#' stored terms, factor levels, and contrasts. \code{type} selects:
#' \describe{
#' \item{\code{"lp"}}{the GCE risk score: the linear predictor centered at
#' the covariate means of the fitting data.}
#' \item{\code{"risk"}}{\code{exp(lp)}, the subject's ratio relative to the
#' average subject.}
#' \item{\code{"ratio"}}{the absolute predicted ratio: \eqn{\omega^{+}(t)}
#' for \code{gcecox} (the marginal Nelson-Aalen ratio
#' \eqn{H_1(t)/H_2(t)} times \code{exp(lp)}), \eqn{\tilde\omega^{+}(t)}
#' for \code{gcefg}, and \eqn{\rho(t)} for \code{gcecif}.}
#' \item{\code{"share"}}{\code{ratio / (1 + ratio)}: \eqn{\omega(t)}, or the
#' share \eqn{\pi_1(t)} for \code{gcecif}.}
#' }
#' \code{times} defaults to the readout time \code{t} of the fit. With several
#' \code{times} a matrix with one column per time is returned. For
#' \code{gcecif} the landmark time is part of the fitted model and cannot be
#' changed. \code{fitted()} is \code{predict()} on the fitting data.
#'
#' @param x,object a fitted model object.
#' @param formula a fitted model object (the argument name is that of the
#' \code{\link[stats]{model.frame}} generic).
#' @param newdata optional data frame of new subjects. If omitted, predictions
#' for the fitting data are returned.
#' @param type type of prediction; see \emph{Prediction}.
#' @param times time(s) at which \code{"ratio"} and \code{"share"} are
#' evaluated.
#' @param parm coefficients for which intervals are wanted (names or indices).
#' @param level confidence level.
#' @param exponentiate logical; return intervals for the ratios
#' \code{exp(coef)} instead of the log ratios.
#' @param conf.level confidence level of the intervals in the summary
#' (defaults to the level used when fitting).
#' @param which display to draw: \code{"riskscore"} (predicted ratio against
#' the risk score, in \code{bins} quantile groups), \code{"omegatime"}
#' (\code{\link{gce_omegatime}}), \code{"alligator"}
#' (\code{\link{gce_alligator}}), or \code{"calibration"}
#' (\code{\link{gce_calibration}}).
#' @param bins number of quantile groups for \code{which = "riskscore"}.
#' @param ylab y-axis label for \code{which = "riskscore"}. The default is
#' the symbol of the ratio estimated by the model.
#' @param digits number of significant digits to print.
#' @param signif.stars logical; print significance stars.
#' @param eps threshold for printing the p-value of the omnibus test: values
#' below \code{eps} are printed as \code{< eps} (see
#' \code{\link[base]{format.pval}}). The p-values in the coefficient table
#' are formatted by \code{\link[stats]{printCoefmat}}, whose
#' \code{eps.Pvalue} argument can be supplied through \code{...}.
#' @param ... for \code{plot}, further arguments passed to the display
#' function; for the \code{print} method of a summary, further arguments
#' passed to \code{\link[stats]{printCoefmat}}; otherwise unused.
#'
#' @return \code{summary} returns an object of class \code{"summary.gcemod"}
#' or \code{"summary.gce_lunnmcneil"}; \code{coef} a named numeric vector
#' (for a summary object, the coefficient matrix);
#' \code{vcov} a matrix; \code{confint} a two-column matrix; \code{logLik}
#' an object of class \code{"logLik"}; \code{predict} and \code{fitted} a
#' numeric vector (or matrix, for several \code{times}); \code{plot} a
#' \code{ggplot} object, invisibly. \code{print} methods return their
#' argument invisibly.
#'
#' @examples
#' data(hn)
#' fit <- gcecox(Surv(time, status) ~ age + smoker + p16, data = hn, t = 5)
#'
#' fit # short display
#' s <- summary(fit) # full table, returned as an object
#' coef(s) # the coefficient table
#' print(s, eps = 1e-8) # p-value formatting of the omnibus test
#' coef(fit); vcov(fit)
#' confint(fit, exponentiate = TRUE)
#' logLik(fit); nobs(fit); formula(fit)
#'
#' head(fitted(fit)) # risk score
#' predict(fit, hn[1:3, ], type = "ratio", times = c(2, 5))
#'
#' fit2 <- update(fit, . ~ . - smoker)
#' plot(fit, which = "riskscore", bins = 5)
#' @name gcemod-methods
#' @aliases gcemod-methods
NULL
# ---- print -----------------------------------------------------------------
.gce_header <- function(x) {
cat(sprintf("Generalized competing event model [%s]\n", x$method))
if (!is.null(x$call))
cat("Call: ", paste(deparse(x$call), collapse = "\n"), "\n", sep = "")
cat(sprintf(" n = %d; events of interest = %d; competing events = %d\n",
x$n, x$n_event, x$n_competing))
}
## Label of the ratio a model estimates. An internal generic: the parent
## class gives the cause-specific label and the specific classes override it.
gce_label <- function(x, ...) UseMethod("gce_label")
#' @export
gce_label.default <- function(x, ...) "omega+ ratio"
#' @export
gce_label.gcefg <- function(x, ...) "omega+ ratio (subdistribution)"
#' @export
gce_label.gcecif <- function(x, ...) "rho ratio"
#' @export
gce_label.gce_lunnmcneil <- function(x, ...) {
if (identical(x$type, "finegray")) "omega+ ratio (subdistribution)"
else NextMethod()
}
#' @rdname gcemod-methods
#' @export
print.gcemod <- function(x, digits = max(3L, getOption("digits") - 3L), ...) {
.gce_header(x)
cat(sprintf("\n%ss, exp(coef)%s:\n", gce_label(x),
if (isTRUE(x$standardize)) " per SD" else ""))
print(exp(stats::coef(x)), digits = digits)
cat("\nUse summary() for standard errors, confidence intervals, and tests.\n")
invisible(x)
}
#' @rdname gcemod-methods
#' @export
print.gce_lunnmcneil <- function(x, digits = max(3L, getOption("digits") - 3L), ...) {
scl <- if (x$type == "finegray") "subdistribution (Fine-Gray)" else "cause-specific (Cox)"
cat(sprintf("Lunn-McNeil stacked model [%s]\n", scl))
if (!is.null(x$call))
cat("Call: ", paste(deparse(x$call), collapse = "\n"), "\n", sep = "")
cat(sprintf(" n = %d; events of interest = %d; competing events = %d\n",
x$n, x$n_event, x$n_competing))
cat(sprintf("\nomega+ ratios, exp(coef)%s:\n",
if (isTRUE(x$standardize)) " per SD" else ""))
print(exp(stats::coef(x)), digits = digits)
cat("\nUse summary() for standard errors, confidence intervals, and tests.\n")
invisible(x)
}
# ---- summary ---------------------------------------------------------------
.gce_summary_core <- function(object, conf.level) {
est <- stats::coef(object)
se <- sqrt(diag(stats::vcov(object)))
## z and p are invariant to the reporting scale (per unit / per SD)
z <- est / se
p <- 2 * stats::pnorm(-abs(z))
tab <- .gce_coeftab(est, se, z, p, conf.level)
list(call = object$call, coefficients = tab$coefficients,
conf.int = tab$conf.int, conf.level = conf.level,
omnibus = object$omnibus, n = object$n, n_event = object$n_event,
n_competing = object$n_competing,
standardize = isTRUE(object$standardize))
}
## Components shared by the two hazard-scale models, which are both fitted
## through a stacked Lunn-McNeil model.
.gce_summary_lm <- function(out, lm) {
out$reference <- lm$beta_competing
out$se_method <- if (identical(lm$se_method, "boot"))
sprintf("subject bootstrap (B = %d)", lm$B) else "cluster-robust (subject)"
out
}
#' @rdname gcemod-methods
#' @export
summary.gcemod <- function(object, conf.level = object$conf.level, ...) {
out <- .gce_summary_core(object, conf.level)
out$method <- object$method
out$label <- gce_label(object)
out$t <- object$t
out$title <- "Generalized competing event model"
out$se_method <- "cluster-robust (subject)"
class(out) <- "summary.gcemod"
out
}
#' @rdname gcemod-methods
#' @export
summary.gcecox <- function(object, conf.level = object$conf.level, ...) {
out <- NextMethod()
out <- .gce_summary_lm(out, object$lunnmcneil)
out$baseline <- c(`omega+` = object$w0plus,
omega = object$w0plus / (1 + object$w0plus))
out
}
#' @rdname gcemod-methods
#' @export
summary.gcefg <- function(object, conf.level = object$conf.level, ...) {
out <- NextMethod()
.gce_summary_lm(out, object$lunnmcneil)
}
#' @rdname gcemod-methods
#' @export
summary.gcecif <- function(object, conf.level = object$conf.level, ...) {
out <- NextMethod()
out$baseline <- c(F1 = object$F1, F2 = object$F2, rho = object$rho0)
out$converged <- object$converged
out$se_method <- "cluster-robust sandwich (subject)"
out
}
#' @rdname gcemod-methods
#' @export
summary.gce_lunnmcneil <- function(object, conf.level = object$conf.level, ...) {
out <- .gce_summary_core(object, conf.level)
out$method <- if (object$type == "finegray") "subdistribution (Fine-Gray)"
else "cause-specific (Cox)"
out$label <- gce_label(object)
out$title <- "Lunn-McNeil stacked model"
out <- .gce_summary_lm(out, object)
class(out) <- c("summary.gce_lunnmcneil", "summary.gcemod")
out
}
#' @rdname gcemod-methods
#' @export
print.summary.gcemod <- function(x, digits = max(3L, getOption("digits") - 3L),
signif.stars = getOption("show.signif.stars"),
eps = 1e-4, ...) {
cat(x$title, sprintf(" [%s]\n", x$method), sep = "")
if (!is.null(x$call))
cat("Call: ", paste(deparse(x$call), collapse = "\n"), "\n", sep = "")
cat(sprintf(" n = %d; events of interest = %d; competing events = %d\n",
x$n, x$n_event, x$n_competing))
if (!is.null(x$baseline)) {
if ("F1" %in% names(x$baseline)) {
cat(sprintf(" at t = %g: F1(t) = %.4f; F2(t) = %.4f; rho(t) = F1/F2 = %.4f\n",
x$t, x$baseline[["F1"]], x$baseline[["F2"]], x$baseline[["rho"]]))
} else {
cat(sprintf(" at t = %g: omega+(t) = %.4f; omega(t) = %.4f (average subject)\n",
x$t, x$baseline[["omega+"]], x$baseline[["omega"]]))
}
}
cat(sprintf("\nCoefficients (log %s%s):\n", x$label,
if (isTRUE(x$standardize)) ", per SD" else ""))
stats::printCoefmat(x$coefficients, digits = digits,
signif.stars = signif.stars, P.values = TRUE,
has.Pvalue = TRUE, na.print = "NA", ...)
cat(sprintf("\n%s with %s%% confidence interval:\n",
sub("^(.)", "\\U\\1", x$label, perl = TRUE),
format(100 * x$conf.level)))
print(format(as.data.frame(x$conf.int), digits = digits), quote = FALSE)
if (!is.null(x$omnibus) && !is.na(x$omnibus["statistic"])) {
cat(sprintf("\nOmnibus Wald test (all ratios = 1): chi-sq = %.3f on %d df, p = %s\n",
x$omnibus["statistic"], as.integer(x$omnibus["df"]),
.fmt_p(x$omnibus["p.value"], eps = eps)))
}
cat(sprintf("Standard errors: %s\n", x$se_method))
if (isFALSE(x$converged))
cat("Note: the estimating equations did not converge.\n")
invisible(x)
}
# ---- extractors ------------------------------------------------------------
#' @rdname gcemod-methods
#' @export
coef.gcemod <- function(object, ...) object$coef
#' @rdname gcemod-methods
#' @export
coef.gce_lunnmcneil <- function(object, ...) object$coef
#' @rdname gcemod-methods
#' @export
coef.summary.gcemod <- function(object, ...) object$coefficients
#' @rdname gcemod-methods
#' @export
vcov.gcemod <- function(object, ...) object$var
#' @rdname gcemod-methods
#' @export
vcov.gce_lunnmcneil <- function(object, ...) object$var
.gce_confint <- function(object, parm, level, exponentiate) {
cf <- stats::coef(object)
se <- sqrt(diag(stats::vcov(object)))
pn <- names(cf)
if (missing(parm)) parm <- pn else if (is.numeric(parm)) parm <- pn[parm]
a <- (1 - level) / 2
ci <- cbind(cf[parm] + stats::qnorm(a) * se[parm],
cf[parm] + stats::qnorm(1 - a) * se[parm])
dimnames(ci) <- list(parm, paste(format(100 * c(a, 1 - a), trim = TRUE,
digits = 3), "%"))
if (isTRUE(exponentiate)) exp(ci) else ci
}
#' @rdname gcemod-methods
#' @export
confint.gcemod <- function(object, parm, level = 0.95, exponentiate = FALSE, ...)
.gce_confint(object, parm, level, exponentiate)
#' @rdname gcemod-methods
#' @export
confint.gce_lunnmcneil <- function(object, parm, level = 0.95,
exponentiate = FALSE, ...)
.gce_confint(object, parm, level, exponentiate)
#' @rdname gcemod-methods
#' @export
nobs.gcemod <- function(object, ...) object$n
#' @rdname gcemod-methods
#' @export
nobs.gce_lunnmcneil <- function(object, ...) object$n
#' @rdname gcemod-methods
#' @export
formula.gcemod <- function(x, ...) x$formula
#' @rdname gcemod-methods
#' @export
formula.gce_lunnmcneil <- function(x, ...) x$formula
#' @rdname gcemod-methods
#' @export
terms.gcemod <- function(x, ...) x$terms
#' @rdname gcemod-methods
#' @export
terms.gce_lunnmcneil <- function(x, ...) x$terms
#' @rdname gcemod-methods
#' @export
model.frame.gcemod <- function(formula, ...) {
if (is.null(formula$model))
stop("The model frame was not stored; refit with model = TRUE.", call. = FALSE)
formula$model
}
#' @rdname gcemod-methods
#' @export
model.matrix.gcemod <- function(object, ...) object$design
.gce_logLik <- function(fit, n) {
structure(fit$loglik[length(fit$loglik)], df = length(stats::coef(fit)),
nobs = n, class = "logLik")
}
#' @rdname gcemod-methods
#' @export
logLik.gcemod <- function(object, ...)
.gce_logLik(object$lunnmcneil$fit, object$n)
#' @rdname gcemod-methods
#' @export
logLik.gcecif <- function(object, ...)
stop("gcecif() models are estimated by generalized estimating equations ",
"on pseudo-observations and have no likelihood.", call. = FALSE)
#' @rdname gcemod-methods
#' @export
logLik.gce_lunnmcneil <- function(object, ...) .gce_logLik(object$fit, object$n)
# ---- prediction ------------------------------------------------------------
## The risk score (centered linear predictor) is computed in the same way for
## every model: design matrix for the fitting data or for 'newdata', the linear
## predictor, and the names to attach to the result.
.gce_lp <- function(object, newdata) {
cn <- object$covnames
X <- if (is.null(newdata)) object$design else .gce_newX(object, newdata)
lp <- as.numeric(sweep(X, 2, object$center[cn], "-") %*% object$coef_raw[cn])
nm <- rownames(X)
if (!is.null(newdata) && is.null(nm)) nm <- rownames(newdata)
if (is.null(newdata)) nm <- NULL
list(X = X, lp = lp, names = nm)
}
.gce_times <- function(times, t) {
if (is.null(times)) times <- t
if (!is.numeric(times) || any(times <= 0))
stop("'times' must be positive.", call. = FALSE)
times
}
## Shape a subjects-by-times matrix of predicted ratios into the returned value.
.gce_ratio_out <- function(ratio, type, times, nm) {
if (length(times) == 1L) ratio <- as.numeric(ratio)
else dimnames(ratio) <- list(nm, paste0("t=", format(times, trim = TRUE)))
out <- if (type == "ratio") ratio else ratio / (1 + ratio)
if (is.null(dim(out))) stats::setNames(out, nm) else out
}
#' @rdname gcemod-methods
#' @export
predict.gcemod <- function(object, newdata = NULL,
type = c("lp", "risk", "ratio", "share"),
times = NULL, ...) {
type <- match.arg(type)
if (!type %in% c("lp", "risk"))
stop("type = \"", type, "\" is not available for objects of class \"",
class(object)[1L], "\".", call. = FALSE)
pr <- .gce_lp(object, newdata)
stats::setNames(if (type == "lp") pr$lp else exp(pr$lp), pr$names)
}
#' @rdname gcemod-methods
#' @export
predict.gcecox <- function(object, newdata = NULL,
type = c("lp", "risk", "ratio", "share"),
times = NULL, ...) {
type <- match.arg(type)
if (type %in% c("lp", "risk")) return(NextMethod())
pr <- .gce_lp(object, newdata)
times <- .gce_times(times, object$t)
w0 <- .cumhaz_at(object$cumhaz$event, times) /
.cumhaz_at(object$cumhaz$competing, times)
.gce_ratio_out(outer(exp(pr$lp), w0), type, times, pr$names)
}
#' @rdname gcemod-methods
#' @export
predict.gcefg <- function(object, newdata = NULL,
type = c("lp", "risk", "ratio", "share"),
times = NULL, ...) {
type <- match.arg(type)
if (type %in% c("lp", "risk")) return(NextMethod())
pr <- .gce_lp(object, newdata)
times <- .gce_times(times, object$t)
H <- .gcefg_H(object, pr$X, times)
.gce_ratio_out(t(H$H1 / H$H2), type, times, pr$names) # subjects x times
}
#' @rdname gcemod-methods
#' @export
predict.gcecif <- function(object, newdata = NULL,
type = c("lp", "risk", "ratio", "share"),
times = NULL, ...) {
type <- match.arg(type)
if (type %in% c("lp", "risk")) return(NextMethod())
if (!is.null(times) && !isTRUE(all.equal(times, object$t)))
stop("A gcecif() model is specific to its landmark time (t = ",
format(object$t), "); refit to predict at another time.",
call. = FALSE)
pr <- .gce_lp(object, newdata)
ratio <- exp(as.numeric(cbind(1, pr$X) %*% object$coef_rho))
stats::setNames(if (type == "ratio") ratio else ratio / (1 + ratio), pr$names)
}
#' @rdname gcemod-methods
#' @export
fitted.gcemod <- function(object, type = c("lp", "risk", "ratio", "share"), ...)
stats::predict(object, type = match.arg(type), ...)
# ---- plot ------------------------------------------------------------------
#' @rdname gcemod-methods
#' @export
plot.gcemod <- function(x, which = c("riskscore", "omegatime", "alligator",
"calibration"), bins = 5,
ylab = expression(omega^"+"), ...) {
which <- match.arg(which)
if (which == "omegatime") return(plot(gce_omegatime(x, ...)))
if (which == "alligator") return(plot(gce_alligator(x, ...)))
if (which == "calibration") return(plot(gce_calibration(x, ...)))
.gce_pos(bins, "bins")
ratio <- stats::predict(x, type = "ratio")
qb <- seq(0, 1, length.out = bins + 1)[-1]
p <- .gce_scatter(stats::quantile(x$normCER, probs = qb, na.rm = TRUE),
stats::quantile(ratio, probs = qb, na.rm = TRUE),
"Risk score (standardized)", ylab)
print(p)
invisible(p)
}
#' @rdname gcemod-methods
#' @export
plot.gcefg <- function(x, ..., ylab = expression(tilde(omega)^"+"))
NextMethod(ylab = ylab)
#' @rdname gcemod-methods
#' @export
plot.gcecif <- function(x, ..., ylab = expression(rho))
NextMethod(ylab = ylab)
#' Tidy a GCE model into a data frame of estimates
#'
#' With \code{effects = FALSE} (the default) the omega+ ratio estimates are
#' returned. With \code{effects = TRUE} a covariate-effects comparison table is
#' returned that juxtaposes, for each covariate, the hazard ratio for the primary
#' (event-of-interest) hazard, the competing-event hazard, the total (composite,
#' any-event) hazard, and the relative hazard ratio (the omega+ ratio) from the
#' GCE model, each with a confidence interval. This lets the investigator see
#' whether a covariate acts mainly on the event of interest, the competing event,
#' both, or on their balance.
#'
#' The individual- and total-event columns are estimated on the same hazard scale
#' as the fitted model: cause-specific Cox models for a \code{\link{gcecox}} fit,
#' and Fine-Gray subdistribution models for a \code{\link{gcefg}} fit. The total
#' (composite) event has no competing event, so its subdistribution and
#' cause-specific hazards coincide and a Cox model on the composite endpoint is
#' used in both cases.
#'
#' @param object a \code{"gcemod"} object from \code{\link{gcecox}},
#' \code{\link{gcefg}}, or \code{\link{gcecif}}. For a \code{\link{gcecif}} fit
#' the \code{relative} column is the cumulative-incidence ratio (rho ratio) and
#' the primary/competing/total columns are cause-specific hazard ratios.
#' @param effects logical; if \code{TRUE}, return the primary/competing/total/
#' relative effects comparison table instead of the omega+ ratio table.
#' Requires an object fit with \pkg{gcemod} >= 0.3.0 (which stores the design
#' matrix). Default \code{FALSE}.
#' @param ... unused.
#' @return If \code{effects = FALSE}, a data frame with columns \code{term},
#' \code{log_ratio}, \code{ratio}, \code{conf.low}, \code{conf.high},
#' \code{p.value}. If \code{effects = TRUE}, a data frame with columns
#' \code{term}, \code{primary}, \code{competing}, \code{total}, and
#' \code{relative}, each a formatted "HR (low, high)" string.
#' @examples
#' data(hn)
#' fit <- gcecox(Surv(time, status) ~ age + t_cat + p16, data = hn, t = 5)
#' gce_tidy(fit)
#' gce_tidy(fit, effects = TRUE)
#' @export
gce_tidy <- function(object, effects = FALSE, ...) {
if (!inherits(object, "gcemod")) stop("'object' must be a gcemod object.", call. = FALSE)
tab <- object$result
base <- data.frame(
term = rownames(tab),
log_ratio = as.numeric(object$coef),
ratio = as.numeric(tab[, 1]),
conf.low = as.numeric(tab[, 2]),
conf.high = as.numeric(tab[, 3]),
p.value = as.numeric(tab[, 4]),
row.names = NULL,
stringsAsFactors = FALSE
)
if (!isTRUE(effects)) return(base)
X <- object$design
if (is.null(X))
stop("This object does not carry a design matrix; refit with gcemod >= 0.3.0 ",
"to use 'effects = TRUE'.", call. = FALSE)
time <- object$time
cause <- object$cause
cn <- object$covnames
z <- stats::qnorm(1 - (1 - object$conf.level) / 2)
fmt <- function(b, se) sprintf("%.2f (%.2f, %.2f)",
exp(b), exp(b - z * se), exp(b + z * se))
## coefficients come back in the column order of X (== cn), so align by position
cox_hr <- function(ev) {
f <- survival::coxph(survival::Surv(time, ev) ~ X)
fmt(stats::coef(f), sqrt(diag(stats::vcov(f))))
}
crr_hr <- function(fit) fmt(fit$coef, sqrt(diag(fit$var)))
if (inherits(object, "gcefg")) { # subdistribution scale
primary <- crr_hr(object$fit1)
competing <- crr_hr(object$fit2)
} else { # cause-specific (Cox) scale
primary <- cox_hr(as.integer(cause == 1L))
competing <- cox_hr(as.integer(cause == 2L))
}
total <- cox_hr(as.integer(cause > 0L)) # composite endpoint: no competing event
relative <- sprintf("%.2f (%.2f, %.2f)", base$ratio, base$conf.low, base$conf.high)
data.frame(
term = cn,
primary = primary,
competing = competing,
total = total,
relative = relative,
row.names = NULL,
stringsAsFactors = FALSE
)
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.