---
title: "Competing risk survival"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Competing risk survival}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE, warning = FALSE, message = FALSE,
  out.width = "100%",
  comment = "#>"
)
```

## Set up

Let us first load the packages required.

```{r}
library(CDMConnector)
library(CohortSurvival)
library(dplyr)
library(ggplot2)
```

We will create a cdm reference to use our example MGUS2 survival dataset again. In practice you would use the CDMConnector package to connect to your data mapped to the OMOP CDM.

```{r}
cdm <- CohortSurvival::mockMGUS2cdm()
```

We will proceed as we did with the single event survival, but this time we are considering an event of interest (progression of disease) with a competing risk (mortality). A competing outcome is an event that changes the interpretation of follow-up because, once it occurs, the event of interest can no longer be observed in the same way. In this example, death competes with later observed progression.

All the details provided in the single event survival vignette are also valid in this study case: the potential input changes for the estimation, the different output formats available or the options for the table and plot functions. Everything discussed previously is also applicable when adding a competing outcome, as we will show in this vignette. Therefore we will not provide as much detail in all the possible combinations of inputs here, but rather focus in the particularities of estimating survival with an outcome and a competing outcome.

Let us take a glimpse at the three cohorts we will use this time: the mgus diagnosis as a target, and both the death cohort and the progression to multiple myeloma as outcomes.

```{r}
cdm$mgus_diagnosis |> 
  glimpse()

cdm$death_cohort |> 
  glimpse()

cdm$progression |>
  glimpse()
```

## Estimating survival with competing risk

This package allows to estimate the cumulative incidence of both an outcome and a competing outcome. We can then stratify, see information on events or summarise the estimates, among others, in the same way we did for the single event survival analysis. The only additional requirement here is to specify the `competingOutcomeCohortTable` argument.

```{r, fig.width=5}
MGUS_death_prog <- estimateCompetingRiskSurvival(cdm,
  targetCohortTable = "mgus_diagnosis",
  outcomeCohortTable = "progression",
  competingOutcomeCohortTable = "death_cohort"
) 

MGUS_death_prog |> 
  asSurvivalResult() |> 
  glimpse()
```

As we can see above our results have been outputted in long format, once transformed into the survival format. For competing-risk results, `estimate` is interpreted as cumulative incidence for the row's `variable`, which will be either the outcome of interest or the competing outcome. This is why we use `cumulativeFailure = TRUE` when plotting:

```{r, out.width = "75%"}
plotSurvival(MGUS_death_prog, cumulativeFailure = TRUE,
             colour = "variable") + 
  theme(legend.position = "top")
```

The summary table of survival now has a row for each of the outcomes:

```{r}
tableSurvival(MGUS_death_prog) 
```

The restricted mean summary follows the same principle as in the single-event analysis: it is calculated up to `restrictedMeanFollowUp`. If `restrictedMeanFollowUp = NULL`, the horizon is left to the underlying survival summary. In stratified analyses, this can use a common maximum follow-up time across the fitted curves. A stratum with shorter observed follow-up may therefore have its last estimate carried forward and integrated beyond its own maximum follow-up. This can make restricted mean summaries larger than the observed follow-up time for some strata and can make comparisons misleading. For comparisons, set a common clinically meaningful horizon in `estimateCompetingRiskSurvival()` that is supported by follow-up in all groups, for example `restrictedMeanFollowUp = 365`.

The outcome and competing outcome can have separate washout definitions. `outcomeWashout` controls prior events of the outcome of interest, while `competingOutcomeWashout` controls prior competing events. In both cases, `Inf` means any prior event before target cohort entry and `0` means no pre-index washout. Other censoring parameters, such as `followUpDays`, `censorOnCohortExit`, and `censorOnDate`, behave as in the single-event setting.

## With stratification

Again, to estimate survival for particular strata of interest we need these features to have been added to the target cohort table. We can then give the names of these strata columns to the estimating function like so:

```{r}
MGUS_death_prog <-  estimateCompetingRiskSurvival(cdm,
  targetCohortTable = "mgus_diagnosis",
  outcomeCohortTable = "progression",
  competingOutcomeCohortTable = "death_cohort",
  strata = list(c("sex"))
)

```

As well as results for each strata, we will always also have overall results returned. We can filter the output table to plot only the results for the different strata levels, if we do not wish to add the overall cohort in the plot. We can also ask for the cumulative failure probability to be plotted instead of the survival probability, which makes more sense in the competing outcome case.

```{r, fig.height=6, fig.width=8}
plotSurvival(MGUS_death_prog |> 
               dplyr::filter(strata_name != "Overall"), 
             facet = "sex",
             colour = "variable",
             cumulativeFailure = TRUE)
```

And we also now have summary statistics for each of the strata as well as overall.

```{r}
tableSurvival(MGUS_death_prog)
```

## Disconnect from the cdm database connection

As always, we finish by disconnecting from the cdm.

```{r}
cdmDisconnect(cdm)
```
