--- title: "Worked examples" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Worked examples} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r worked-setup, include=FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "fig/worked-", fig.width = 6, fig.height = 4, fig.align = "center", out.width = "75%" ) if (!requireNamespace("cifmodeling", quietly = TRUE)) { stop("Package 'cifmodeling' is required to build this vignette.") } library(cifmodeling) data("diabetes.complications", package = "cifmodeling") # Check the output used in the explanatory paragraphs. # Use the same checks for the event-specific and composite risk tables. # A missing group, out-of-support time, or unavailable CI must not silently # remove the interpretation paragraph from a published vignette. check_eight_year_risks <- function(x, description) { expected <- c("Other intake", "Low intake") if (nrow(x) != length(expected) || anyNA(x$group) || anyDuplicated(x$group) || !setequal(x$group, expected)) { stop(description, ": expected exactly one eight-year estimate per group.", call. = FALSE) } z <- as.matrix(x[, c("risk", "conf.low", "conf.high"), drop = FALSE]) tol <- 1e-10 if (any(!is.finite(z)) || any(z < -tol | z > 1 + tol) || any(x$conf.low > x$conf.high + tol) || any(x$risk < x$conf.low - tol | x$risk > x$conf.high + tol)) { stop(description, ": a risk or confidence limit is missing or inconsistent; ", "check the follow-up support and the fit's conf.status.", call. = FALSE) } invisible(x) } ``` We use one dataset to answer four related questions with `cifmodeling`: 1. What is the probability of each complication by eight years? 2. Is there evidence that the retinopathy CIFs differ between fruit-intake groups? 3. How large is the eight-year risk ratio for each complication? 4. What changes if the outcome is the **first occurrence of either complication**? We show the main function calls and their results. Interpretation paragraphs are generated from fitted objects when the vignette is built; verification checks also run, but their code is hidden so the examples stay easy to follow. For plot styling and complete argument lists, see [Gallery](v6_gallery.html) and [Function reference](v9_arguments.html). ## Data and endpoints The `diabetes.complications` dataset contains anonymized observations from the Japan Diabetes Complications Study. Tanaka et al. (2013) examined the association between fruit intake and incident retinopathy in this cohort. We use the following variables: | Variable | Meaning | |:--|:--| | `t` | Follow-up time, in years | | `epsilon = 0` | Censored observation | | `epsilon = 1` | Diabetic retinopathy (event of interest) | | `epsilon = 2` | Macrovascular complication (competing event) | | `fruitq` | Quartile of fruit intake | We compare the lowest fruit-intake quartile (Q1) with the other three quartiles (Q2–Q4). The [Overview](v1_overview.html) uses the supplied `fruitq1` indicator for the same comparison. Here we reconstruct it from `fruitq`: a factor for plots and tests, and a binary variable for regression. **Other intake (0)** is the reference group. ```{r worked-data} analysis_data <- diabetes.complications analysis_data$low_fruit <- as.integer(analysis_data$fruitq == "Q1") analysis_data$fruit_group <- factor( analysis_data$low_fruit, levels = c(0, 1), labels = c("Other intake", "Low intake") ) # Check the size of each group and the observed first-event codes. table( Fruit_intake = analysis_data$fruit_group, First_event = factor( analysis_data$epsilon, levels = c(0, 1, 2), labels = c("Censored", "Retinopathy", "Macrovascular") ) ) ``` The table reports **observed first-event counts**, not event probabilities. Estimating cumulative incidence requires accounting for censoring and differences in follow-up. The comparisons below describe associations in observational data; they do not, by themselves, establish causal effects of fruit intake. ## 1. Estimate cumulative incidence We begin with the **cumulative incidence function (CIF)** of diabetic retinopathy in each group. Macrovascular complications may occur first and prevent retinopathy from being the first recorded event. `cifcurve()` therefore uses the Aalen–Johansen estimator rather than treating competing events as ordinary censoring. ```{r worked-cif} fit_cif <- cifcurve( Event(t, epsilon) ~ fruit_group, data = analysis_data, outcome.type = "competing-risk", code.event1 = 1, code.event2 = 2 ) ``` The eight-year estimates are obtained from `summary(fit_cif, times = 8)`. The table reports the event-1 CIF, rather than the complementary probability stored in the `surv` column. ```{r worked-cif-prepare, include=FALSE} at_eight <- summary(fit_cif, times = 8) cif_eight <- data.frame( group = sub("^[^=]*=", "", as.character(at_eight$strata)), risk = 1 - at_eight$surv, conf.low = 1 - at_eight$upper, conf.high = 1 - at_eight$lower ) check_eight_year_risks(cif_eight, "Retinopathy CIF") ``` ```{r worked-cif-table, echo=FALSE} data.frame( group = cif_eight$group, risk_percent = round(100 * cif_eight$risk, 1), CI_low_percent = round(100 * cif_eight$conf.low, 1), CI_high_percent = round(100 * cif_eight$conf.high, 1) ) ``` For competing-risk fits, `cifcurve()` stores **one minus the event-1 CIF** in `surv`, with confidence limits on the same complementary scale. To report a CIF interval, use `1 - upper` for the lower limit and `1 - lower` for the upper limit. These are **pointwise** intervals for each group—not simultaneous bands or intervals for the *between-group difference*. The probability of remaining free of **both** events is a different quantity (see Section 4 and [Computational formulas](v4_formulas.html)). For these unweighted CIFs, the default 95% pointwise intervals use a **delta-method standard error**, an **arcsine-square-root transformation**, and a **normal reference distribution**. [Computational formulas](v4_formulas.html) describes other options, including influence-function and Student-reference intervals. ```{r worked-cif-interpret, echo=FALSE, results='asis'} # Estimates and limits were validated in the preceding chunk. low <- cif_eight[cif_eight$group == "Low intake", , drop = FALSE] other <- cif_eight[cif_eight$group == "Other intake", , drop = FALSE] cat(sprintf( "**Reading the estimate.** At eight years, retinopathy occurred first with estimated probabilities of **%.1f%%** in the low-intake group and **%.1f%%** in the other-intake group. The difference between these two *point estimates* was **%+.1f percentage points**. This is a descriptive contrast, not a confidence interval or a test of the group difference.\n\n", 100 * low$risk, 100 * other$risk, 100 * (low$risk - other$risk) )) ``` ```{r worked-cif-plot, fig.cap="Cumulative incidence of diabetic retinopathy by fruit-intake group", warning=FALSE, message=FALSE} cifplot( fit_cif, type.y = "risk", add.risktable = FALSE, add.censor.mark = FALSE, label.x = "Years from registration", label.y = "Cumulative incidence of retinopathy", limits.x = c(0, 8) ) ``` The plot displays the event-1 CIF over follow-up. To view **both** competing events side by side, use `cifpanel()` and swap the event codes in the second panel: ```{r worked-two-events, fig.cap="Cumulative incidence of both competing events", warning=FALSE, message=FALSE} fit_panels <- cifpanel( formula = Event(t, epsilon) ~ fruit_group, data = analysis_data, outcome.type = "competing-risk", code.events = list(c(1, 2, 0), c(2, 1, 0)), rows.columns.panel = c(1, 2), title.plot = c("Diabetic retinopathy", "Macrovascular complication"), legend.collect = TRUE ) print(fit_panels) ``` Each `code.events` vector lists the event of interest, competing event, and censoring code, in that order. For panel layout, labels, risk tables, and event marks, see [Gallery](v6_gallery.html). ## 2. Compare cumulative incidence between groups The plots show how the groups differ descriptively, but do not test equality of the CIFs. Use `ciftest(test = "gray")` for the classical **Gray test**: ```{r worked-gray} fit_gray <- ciftest( Event(t, epsilon) ~ fruit_group, data = analysis_data, outcome.type = "competing-risk", test = "gray" ) fit_gray ``` `ciftest()` also provides an **augmented score test** based on working event and censoring distributions. For competing-risk outcomes, `test = "auto"` selects this method: ```{r worked-augmented} fit_augmented <- ciftest( Event(t, epsilon) ~ fruit_group, data = analysis_data, outcome.type = "competing-risk", test = "auto" ) fit_augmented ``` The two tests use different scores and variance estimators, but both assess equality of the **retinopathy CIF over follow-up**. Neither directly estimates the eight-year RR, and a p-value does not measure the size of the group difference. ```{r worked-test-interpret, echo=FALSE, results='asis'} p_gray <- fit_gray$p.value p_aug <- fit_augmented$p.value p_values <- c(p_gray, p_aug) if (length(p_gray) != 1L || length(p_aug) != 1L || any(!is.finite(p_values)) || any(p_values < 0 | p_values > 1)) { stop("Gray or augmented-score p-value is unavailable or invalid; ", "check the fitted test and analysis data.", call. = FALSE) } gray_evidence <- if (p_gray < 0.05) { "provides evidence against equal CIFs" } else { "does not provide strong evidence against equal CIFs" } cat(sprintf( "**Reading the tests.** The Gray test gives **p = %s** and the augmented score test gives **p = %s**. At an illustrative 5%% threshold, the Gray result %s. A non-significant result is not proof of equal CIFs. The two procedures test the same equality of CIFs but use different scores and variance estimates; their p-values should not be compared to select whichever test happens to be significant.\n\n", format.pval(p_gray, digits = 3, eps = 0.001), format.pval(p_aug, digits = 3, eps = 0.001), gray_evidence )) ``` For early- or late-weighted scores, multiple-direction quadratic tests, and one- or two-sided max tests, see [Tests of cumulative incidence functions](v3_gray_extensions.html). ## 3. Estimate eight-year risk ratios To quantify the group comparison at eight years, `polyreg()` jointly models both competing events and estimates their **risk ratios (RRs)**. This first fit gives **unadjusted (crude) RRs**. The exposure is specified separately from `nuisance.model`; `~ 1` indicates that no additional covariates are included. ```{r worked-unadjusted-rr, warning=FALSE, message=FALSE} fit_rr <- polyreg( nuisance.model = Event(t, epsilon) ~ 1, exposure = "low_fruit", data = analysis_data, code.exposure.ref = 0, outcome.type = "competing-risk", time.point = 8, effect.measure1 = "RR", effect.measure2 = "RR" ) summary(fit_rr) ``` The `summary()` output reports fitted exposure effects. To make the two cause-specific RRs easier to compare, the table below extracts their 95% CIs. The extraction and validity checks run during the build but are not shown. ```{r worked-rr-prepare, include=FALSE} # Show only the exposure effects, not the nuisance coefficients. event_labels <- c(event1 = "Retinopathy", event2 = "Macrovascular complication") rr_eight <- do.call(rbind, lapply(names(event_labels), function(event) { estimates <- generics::tidy( fit_rr, event = event, conf.int = TRUE, exponentiate = TRUE ) exposure_terms <- fit_rr$reporting$events[[event]]$term selected <- estimates[match(exposure_terms, estimates$term), , drop = FALSE] if (nrow(selected) != 1L || anyNA(selected$term)) { stop("Expected one exposure contrast per event") } data.frame( event = unname(event_labels[event]), RR = selected$estimate, conf.low = selected$conf.low, conf.high = selected$conf.high ) })) rownames(rr_eight) <- NULL if (nrow(rr_eight) != length(event_labels) || anyNA(rr_eight$event) || !setequal(rr_eight$event, unname(event_labels))) { stop("Expected one RR estimate for each competing event.", call. = FALSE) } rr_values <- as.matrix(rr_eight[, c("RR", "conf.low", "conf.high"), drop = FALSE]) if (any(!is.finite(rr_values)) || any(rr_values <= 0) || any(rr_eight$conf.low > rr_eight$conf.high)) { stop("A competing-event RR or confidence interval is missing or invalid.", call. = FALSE) } ``` ```{r worked-rr-table, echo=FALSE} data.frame( event = rr_eight$event, RR = round(rr_eight$RR, 2), CI_low = round(rr_eight$conf.low, 2), CI_high = round(rr_eight$conf.high, 2) ) ``` Each RR compares **low intake** with **other intake** for one event at eight years. A value of 1 indicates equal modeled risks; values above or below 1 indicate higher or lower risk, respectively, in the low-intake group. The joint model ensures that the event probabilities remain coherent: their sum cannot exceed one. ```{r worked-rr-interpret, echo=FALSE, results='asis'} for (j in seq_len(nrow(rr_eight))) { x <- rr_eight[j, ] ci_message <- if (x$conf.low <= 1 && x$conf.high >= 1) { "The 95% CI includes 1; both directions of association remain compatible with the data." } else { "The 95% CI does not include 1, under this model and variance estimator." } cat(sprintf( "For **%s**, the estimated eight-year RR was **%.2f** (95%% CI **%.2f–%.2f**). %s\n\n", x$event, x$RR, x$conf.low, x$conf.high, ci_message )) } ``` A ratio formed from separately estimated AJ CIFs and an unadjusted `polyreg()` RR both describe the eight-year risk comparison, but they need not agree numerically. The estimation procedures differ in their estimating equations, handling of censoring, and use of a joint probability model. An RR confidence interval should not be interpreted as an interval for the absolute risk difference. For a more detailed model, include baseline covariates in `nuisance.model` and use `strata` to specify how the censoring distribution is estimated. The next code block retains the original vignette's fuller covariate specification. It is **not executed during the build** because fitting this model can be computationally intensive. ```{r worked-adjusted-rr, eval=FALSE} fit_adjusted <- polyreg( nuisance.model = Event(t, epsilon) ~ age + sex + bmi + hba1c + diabetes_duration + drug_oha + drug_insulin + sbp + ldl + hdl + tg + current_smoker + alcohol_drinker + ltpa, exposure = "low_fruit", strata = "strata", data = analysis_data, code.exposure.ref = 0, outcome.type = "competing-risk", time.point = 8, effect.measure1 = "RR", effect.measure2 = "RR" ) summary(fit_adjusted) ``` Here `strata` determines the censoring-weight strata, not the exposure groups. Differences from the unadjusted fit may reflect both covariate adjustment and the censoring model. Causal interpretation additionally requires appropriate confounding and censoring assumptions. See [Direct polytomous regression](v2_polyreg.html) for model details and other effect measures, and [Reporting results](v7_reporting_results.html) for formatted tables. ## 4. Consider a combined survival endpoint We now consider **time to the first complication of either type**. For this composite endpoint, both retinopathy and macrovascular complications count as events. `cifcurve(outcome.type = "survival")` estimates the probability of remaining free of either complication using KM, rather than estimating a cause-specific CIF. ```{r worked-survival} analysis_data$any_complication <- as.integer(analysis_data$epsilon %in% c(1, 2)) fit_survival <- cifcurve( Event(t, any_complication) ~ fruit_group, data = analysis_data, outcome.type = "survival" ) fit_logrank <- ciftest( Event(t, any_complication) ~ fruit_group, data = analysis_data, outcome.type = "survival", test = "logrank" ) fit_logrank ``` `summary(fit_survival, times = 8)` gives the eight-year KM survival probability. The following table shows its complement: the risk of either first complication. ```{r worked-survival-prepare, include=FALSE} # Eight-year probability of any first complication, with its 95% CI. at_eight_composite <- summary(fit_survival, times = 8) composite_eight <- data.frame( group = sub("^[^=]*=", "", as.character(at_eight_composite$strata)), event_free = at_eight_composite$surv, risk = 1 - at_eight_composite$surv, conf.low = 1 - at_eight_composite$upper, conf.high = 1 - at_eight_composite$lower ) check_eight_year_risks(composite_eight, "Composite endpoint") ``` ```{r worked-survival-table, echo=FALSE} data.frame( group = composite_eight$group, event_free_percent = round(100 * composite_eight$event_free, 1), any_complication_percent = round(100 * composite_eight$risk, 1), CI_low_percent = round(100 * composite_eight$conf.low, 1), CI_high_percent = round(100 * composite_eight$conf.high, 1) ) ``` The KM estimate at eight years is the probability of having experienced **neither complication**; its complement is the probability that **at least one** has occurred. The log-rank test compares event-free survival across follow-up, not the risk at eight years alone. ```{r worked-survival-interpret, echo=FALSE, results='asis'} low_comp <- composite_eight[composite_eight$group == "Low intake", , drop = FALSE] other_comp <- composite_eight[composite_eight$group == "Other intake", , drop = FALSE] cat(sprintf( "**Reading the composite endpoint.** The estimated eight-year probability of either first complication was **%.1f%%** in the low-intake group and **%.1f%%** in the other-intake group. This combines two event types and should not be interpreted as the risk of retinopathy alone.\n\n", 100 * low_comp$risk, 100 * other_comp$risk )) ``` ```{r worked-survival-plot, fig.cap="Probability of remaining free of either complication", warning=FALSE, message=FALSE} cifplot( fit_survival, add.risktable = FALSE, add.censor.mark = FALSE, label.x = "Years from registration", label.y = "Probability of no complication", limits.x = c(0, 8) ) ``` The composite risk is related to the two cause-specific CIFs by $$ P(T \leq t, \text{either event}) = F_{\mathrm{retinopathy}}(t) + F_{\mathrm{macrovascular}}(t) = 1 - S_{\mathrm{any\ event}}(t). $$ A second AJ fit lets us check this identity numerically. It also shows why the retinopathy CIF alone is **not** the complement of event-free survival. ```{r worked-event-decomposition} fit_macro <- cifcurve( Event(t, epsilon) ~ fruit_group, data = analysis_data, outcome.type = "competing-risk", code.event1 = 2, code.event2 = 1 ) ``` The table compares the sum of the two AJ CIFs with the complement of the KM event-free survival estimate, using the same groups and time point. ```{r worked-decomposition-prepare, include=FALSE} macro_at_eight <- summary(fit_macro, times = 8) macro_eight <- data.frame( group = sub("^[^=]*=", "", as.character(macro_at_eight$strata)), risk = 1 - macro_at_eight$surv ) check_eight <- merge( merge(cif_eight[c("group", "risk")], macro_eight, by = "group", suffixes = c("_retinopathy", "_macrovascular")), composite_eight[c("group", "risk")], by = "group" ) check_eight$sum_of_CIFs <- check_eight$risk_retinopathy + check_eight$risk_macrovascular names(check_eight)[names(check_eight) == "risk"] <- "composite_risk" ``` ```{r worked-decomposition-table, echo=FALSE} data.frame( group = check_eight$group, sum_of_CIFs_percent = round(100 * check_eight$sum_of_CIFs, 1), composite_risk_percent = round(100 * check_eight$composite_risk, 1) ) ``` The two calculations should agree up to rounding when they use the same first-event definitions, population, and follow-up. This identity does **not** mean that the composite RR is an average or sum of the event-specific RRs. Finally, `polyreg()` can estimate the eight-year RR for the **composite risk**. This is a different estimand from either cause-specific RR. ```{r worked-composite-rr, warning=FALSE, message=FALSE} fit_composite_rr <- polyreg( nuisance.model = Event(t, any_complication) ~ 1, exposure = "low_fruit", data = analysis_data, code.exposure.ref = 0, outcome.type = "survival", time.point = 8, effect.measure1 = "RR" ) summary(fit_composite_rr) ``` ```{r worked-composite-rr-prepare, include=FALSE} # Report the exposure RR and confidence interval on the ratio scale. composite_tidy <- generics::tidy( fit_composite_rr, event = "event1", conf.int = TRUE, exponentiate = TRUE ) composite_terms <- fit_composite_rr$reporting$events$event1$term composite_effect <- composite_tidy[ match(composite_terms, composite_tidy$term), , drop = FALSE ] if (nrow(composite_effect) != 1L || anyNA(composite_effect$term)) { stop("Expected one exposure contrast for the composite endpoint", call. = FALSE) } composite_values <- as.numeric(unlist( composite_effect[1L, c("estimate", "conf.low", "conf.high"), drop = FALSE], use.names = FALSE )) if (any(!is.finite(composite_values)) || any(composite_values <= 0) || composite_values[2L] > composite_values[3L]) { stop("The composite-endpoint RR or confidence interval is missing or invalid.", call. = FALSE) } ``` ```{r worked-composite-rr-table, echo=FALSE} data.frame( RR = round(composite_effect$estimate, 2), CI_low = round(composite_effect$conf.low, 2), CI_high = round(composite_effect$conf.high, 2) ) ``` ```{r worked-composite-interpret, echo=FALSE, results='asis'} cat(sprintf( "**Reading the final RR.** Low versus other fruit intake had an estimated eight-year RR of **%.2f** (95%% CI **%.2f–%.2f**) for *either first complication*. Unlike the retinopathy RR, this effect includes macrovascular first events.\n\n", composite_effect$estimate, composite_effect$conf.low, composite_effect$conf.high )) ``` ## Take-home messages The **AJ CIF** estimates the probability that a specified event occurs first by a given time. **Gray and augmented score tests** compare CIFs across follow-up without estimating a fixed-time effect size. The **`polyreg()` RR** quantifies a fixed-time risk comparison in a coherent model of competing events. For the composite endpoint, the **KM survival curve** instead estimates the probability of remaining free of *both* complications. These quantities are related, but not interchangeable. ## Where to go next - [Direct polytomous regression](v2_polyreg.html) explains the joint model and RR, OR, and SHR options. - [Tests of cumulative incidence functions](v3_gray_extensions.html) covers temporal weights and multiple-direction tests. - [Computational formulas](v4_formulas.html) documents variance and confidence-interval methods. - [Gallery](v6_gallery.html) shows plot customization; [Reporting results](v7_reporting_results.html) shows publication-ready tables. ## References - Tanaka S, Yoshimura Y, Kawasaki R, Kamada C, Tanaka S, Horikawa C, Ohashi Y, Araki A, Ito H, Akanuma Y, Yamada N, Yamashita H, Sone H, for the Japan Diabetes Complications Study Group. Fruit intake and incident diabetic retinopathy with type 2 diabetes. *Epidemiology*. 2013;24(2):204–211. [doi:10.1097/EDE.0b013e318281725e](https://doi.org/10.1097/EDE.0b013e318281725e).