# Introduction to casebase sampling

#### Maxime Turgeon

#### 2024-08-17

## Methodological details

    evaluate_vignette <- requireNamespace("eha", quietly = TRUE) &&
        requireNamespace("visreg", quietly = TRUE) &&
        requireNamespace("splines", quietly = TRUE)
    knitr::opts_chunk$set(eval = evaluate_vignette)

Case-base sampling was proposed by Hanley and Miettinen, 2009 as a way to fit smooth-in-time parametric hazard functions via logistic regression. The main idea, which was first proposed by Mantel, 1973 and then later developed by Efron, 1977, is to sample person-moments, i.e. discrete time points along an subject’s follow-up time, in order to construct a base series against which the case series can be compared.

This approach allows the explicit inclusion of the time variable into the model, which enables the user to fit a wide class of parametric hazard functions. For example, including time linearly recovers the Gompertz hazard, whereas including time logarithmically recovers the Weibull hazard; not including time at all corresponds to the exponential hazard.

The theoretical properties of this approach have been studied in Saarela and Arjas, 2015 and Saarela, 2015.

## Analysis of the `veteran` dataset

The first example we discuss uses the well-known `veteran` dataset, which is part of the `survival` package. As we can see below, there is almost no censoring, and therefore we can get a good visual representation of the survival function:

    set.seed(12345)
    library(casebase)
    library(survival)
    data(veteran)
    table(veteran$status)

    evtimes <- veteran$time[veteran$status == 1]
    hist(evtimes, nclass = 30, main = '', xlab = 'Survival time (days)',
         col = 'gray90', probability = TRUE)
    tgrid <- seq(0, 1000, by = 10)
    lines(tgrid, dexp(tgrid, rate = 1.0/mean(evtimes)),
          lwd = 2, lty = 2, col = 'red')

As we can see, the empirical survival function resembles an exponential distribution.

We will first try to estimate the hazard function parametrically using some well-known regression routines. But first, we will reformat the data slightly.

    veteran$prior <- factor(veteran$prior, levels = c(0, 10), labels = c("no","yes"))
    veteran$celltype <- factor(veteran$celltype,
                               levels = c('large', 'squamous', 'smallcell', 'adeno'))
    veteran$trt <- factor(veteran$trt, levels = c(1, 2), labels = c("standard", "test"))

Using the `eha` package, we can fit a Weibull form, with different values of the shape parameter. For `shape = 1`, we get an exponential distribution:

    library(eha)
    y <- with(veteran, Surv(time, status))

    model1 <- weibreg(y ~ karno + diagtime + age + prior + celltype + trt,
                      data = veteran, shape = 1)
    summary(model1)

If we take `shape = 0`, the shape parameter is estimated along with the regression coefficients:

    model2 <- weibreg(y ~ karno + diagtime + age + prior + celltype + trt,
                      data = veteran, shape = 0)
    summary(model2)

Finally, we can also fit a Cox proportional hazard:

    model3 <- coxph(y ~ karno + diagtime + age + prior + celltype + trt,
                    data = veteran)
    summary(model3)

As we can see, all three models are significant, and they give similar information: `karno` and `celltype` are significant predictors, both treatment is not.

The method available in this package makes use of case-base sampling. That is, person-moments are randomly sampled across the entire follow-up time, with some moments corresponding to cases and others to controls. By sampling person-moments instead of individuals, we can then use logistic regression to fit smooth-in-time parametric hazard functions. See the previous section for more details.

First, we will look at the follow-up time by using population-time plots:

    # create popTime object
    pt_veteran <- popTime(data = veteran)

    class(pt_veteran)

    # plot method for objects of class 'popTime'
    plot(pt_veteran)

Population-time plots are a useful way of visualizing the total follow-up experience, where individuals appear on the y-axis, and follow-up time on the x-axis; each individual’s follow-up time is represented by a gray line segment. For convenience, we have ordered the patients according to their time-to-event, and each event is represented by a red dot. The censored observations (of which there is only a few) correspond to the grey lines which do not end with a red dot.

Next, we use case-base sampling to fit a parametric hazard function via logistic regression. First, we will include time as a linear term; as noted above, this corresponds to an Gompertz hazard.

    model4 <- fitSmoothHazard(status ~ time + karno + diagtime + age + prior +
                 celltype + trt, data = veteran, ratio = 100)
    summary(model4)

Since the output object from `fitSmoothHazard` inherits from the `glm` class, we see a familiar result when using the function `summary`. We can quickly visualize the conditional association between each predictor and the hazard function using the `plot` method for objects that are fit with `fitSmoothHazard`. Specifically, if \(x\) is the predictor of interest, \(h\) is the hazard function, and \(\mathbf{x_{-j}}\) the other predictors in the model, the conditional association plot represents the relationship \(f(x) = \mathbb{E}(h|x, \mathbf{x_{-j}})\). By default, the other terms in the model (\(\mathbf{x_{-j}}\)) are set to their median if the term is numeric or the most common category if the term is a factor. Further details of customizing these plots are given in the `Plot Hazards and Hazard Ratios` vignette.

    library(visreg)
    plot(model4,
         hazard.params = list(alpha = 0.05))

The main purpose of fitting smooth hazard functions is that it is then relatively easy to compute absolute risks. For example, we can use the function `absoluteRisk` to compute the mean absolute risk at 90 days, which can then be compared to the empirical measure.

    absRisk4 <- absoluteRisk(object = model4, time = 90)
    mean(absRisk4)

    ftime <- veteran$time
    mean(ftime <= 90)

We can also fit a Weibull hazard by using a logarithmic term for time:

    model5 <- fitSmoothHazard(status ~ log(time) + karno + diagtime + age + prior +
                 celltype + trt, data = veteran, ratio = 100)
    summary(model5)

With case-base sampling, it is straightforward to fit a semi-parametric hazard function using splines, which can then be used to estimate the mean absolute risk.

    # Fit a spline for time
    library(splines)
    model6 <- fitSmoothHazard(status ~ bs(time) + karno + diagtime + age + prior +
                 celltype + trt, data = veteran, ratio = 100)
    summary(model6)

    str(absoluteRisk(object = model6, time = 90))

As we can see from the summary, there is little evidence that splines actually improve the fit. Moreover, we can see that estimated individual absolute risks are essentially the same when using either a linear term or splines:

    linearRisk <- absoluteRisk(object = model4, time = 90, newdata = veteran)
    splineRisk <- absoluteRisk(object = model6, time = 90, newdata = veteran)

    plot.default(linearRisk, splineRisk,
         xlab = "Linear", ylab = "Splines", pch = 19)
    abline(a = 0, b = 1, lty = 2, lwd = 2, col = 'red')

These last three models give similar information as the first three, i.e. the main predictors for the hazard are `karno` and `celltype`, with treatment being non-significant. Moreover, by explicitly including the time variable in the formula, we see that it is not significant; this is evidence that the true hazard is exponential.

Finally, we can look at the estimates of the coefficients for the Cox model, as well as the last three models (CB stands for “case-base”):

## Cumulative Incidence Curves

Here we show how to calculate the cumulative incidence curves for a specific risk profile using the following equation:

\[ CI(x, t) = 1 - exp\left[ - \int_0^t h(x, u) \textrm{d}u \right] \] where \( h(x, t) \) is the hazard function, \( t \) denotes the numerical value (number of units) of a point in prognostic/prospective time and \( x \) is the realization of the vector \( X \) of variates based on the patient’s profile and intervention (if any).

We compare the cumulative incidence functions from the fully-parametric fit using case base sampling, with those from the Cox model:

    # define a specific covariate profile
    new_data <- data.frame(trt = "test",
                           celltype = "adeno",
                           karno = median(veteran$karno),
                           diagtime = median(veteran$diagtime),
                           age = median(veteran$age),
                           prior = "no")

    # calculate cumulative incidence using casebase model
    smooth_risk <- absoluteRisk(object = model4,
                                time = seq(0,300, 1),
                                newdata = new_data)

    cols <- c("#8E063B","#023FA5")

    # cumulative incidence function for the Cox model
    plot(survfit(model3, newdata = new_data),
         xlab = "Days", ylab = "Cumulative Incidence (%)", fun = "event",
         xlim = c(0,300), conf.int = F, col = cols[1],
         main = sprintf("Estimated Cumulative Incidence (risk) of Lung Cancer\ntrt = test, celltype = adeno, karno = %g,\ndiagtime = %g, age = %g, prior = no", median(veteran$karno), median(veteran$diagtime),
                        median(veteran$age)))

    # add casebase curve with legend
    plot(smooth_risk, add = TRUE, col = cols[2], gg = FALSE)
    legend("bottomright",
           legend = c("semi-parametric (Cox)", "parametric (casebase)"),
           col = cols,
           lty = c(1, 1),
           bg = "gray90")

Note that by default, `absoulteRisk` calculated the cumulative incidence. Alternatively, you can calculate the survival curve by specifying `type = 'survival'` in the call to `absoulteRisk`:

    smooth_risk <- absoluteRisk(object = model4,
                                time = seq(0,300, 1),
                                newdata = new_data,
                                type = "survival")

    plot(survfit(model3, newdata = new_data),
         xlab = "Days", ylab = "Survival Probability (%)",
         xlim = c(0,300), conf.int = F, col = cols[1],
         main = sprintf("Estimated Survival Probability of Lung Cancer\ntrt = test, celltype = adeno, karno = %g,\ndiagtime = %g, age = %g, prior = no", median(veteran$karno), median(veteran$diagtime),
                        median(veteran$age)))

    # add casebase curve with legend
    plot(smooth_risk, add = TRUE, col = cols[2], gg = FALSE)
    legend("topright",
           legend = c("semi-parametric (Cox)", "parametric (casebase)"),
           col = cols,
           lty = c(1, 1),
           bg = "gray90")

## Session information

    ## R version 4.3.3 (2024-02-29)
    ## Platform: x86_64-pc-linux-gnu (64-bit)
    ## Running under: Ubuntu 22.04.4 LTS
    ##
    ## Matrix products: default
    ## BLAS:   /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3
    ## LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.20.so;  LAPACK version 3.10.0
    ##
    ## attached base packages:
    ## [1] stats     graphics  grDevices utils     datasets  methods   base
    ##
    ## other attached packages:
    ## [1] colorspace_2.1-0  data.table_1.15.2 ggplot2_3.5.0     survival_3.5-8
    ## [5] casebase_0.10.6
    ##
    ## loaded via a namespace (and not attached):
    ##  [1] glmnet_4.1-8      Matrix_1.6-5      gtable_0.3.4      jsonlite_1.8.8
    ##  [5] dplyr_1.1.4       compiler_4.3.3    highr_0.10        Rcpp_1.0.12
    ##  [9] tidyselect_1.2.1  VGAM_1.1-11       jquerylib_0.1.4   splines_4.3.3
    ## [13] scales_1.3.0      yaml_2.3.8        fastmap_1.1.1     lattice_0.22-5
    ## [17] R6_2.5.1          labeling_0.4.3    generics_0.1.3    shape_1.4.6.1
    ## [21] knitr_1.45        iterators_1.0.14  tibble_3.2.1      munsell_0.5.0
    ## [25] bslib_0.6.1       pillar_1.9.0      rlang_1.1.3       utf8_1.2.4
    ## [29] cachem_1.0.8      xfun_0.42         sass_0.4.9        cli_3.6.2
    ## [33] withr_3.0.0       magrittr_2.0.3    mgcv_1.9-1        foreach_1.5.2
    ## [37] digest_0.6.35     grid_4.3.3        rstudioapi_0.15.0 lifecycle_1.0.4
    ## [41] nlme_3.1-164      vctrs_0.6.5       evaluate_0.23     glue_1.7.0
    ## [45] farver_2.1.1      codetools_0.2-19  stats4_4.3.3      fansi_1.0.6
    ## [49] rmarkdown_2.26    tools_4.3.3       pkgconfig_2.0.3   htmltools_0.5.7

## References

1. Efron, Bradley. 1977. “The Efficiency of Cox’s Likelihood Function for Censored Data.” Journal of the American Statistical Association 72 (359). Taylor & Francis Group: 557–65.

2. Hanley, James A, and Olli S Miettinen. 2009. “Fitting Smooth-in-Time Prognostic Risk Functions via Logistic Regression.” The International Journal of Biostatistics 5 (1).

3. Mantel, Nathan. 1973. “Synthetic Retrospective Studies and Related Topics.” Biometrics. JSTOR, 479–86.

4. Saarela, Olli. 2015. “A Case-Base Sampling Method for Estimating Recurrent Event Intensities.” Lifetime Data Analysis. Springer, 1–17.

5. Saarela, Olli, and Elja Arjas. 2015. “Non-Parametric Bayesian Hazard Regression for Chronic Disease Risk Assessment.” Scandinavian Journal of Statistics 42 (2). Wiley Online Library: 609–26.

6. Scrucca, L, A Santucci, and F Aversa. 2010. “Regression Modeling of Competing Risk Using R: An in Depth Guide for Clinicians.” Bone Marrow Transplantation 45 (9). Nature Publishing Group: 1388–95.

7. Kalbfleisch, John D., and Ross L. Prentice. The statistical analysis of failure time data. Vol. 360. John Wiley & Sons, 2011.

8. Cox, D. R. “Regression models and life tables.” Journal of the Royal Statistical Society 34 (1972): 187-220.