---
title: "Single outcome event of interest"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Single outcome event of interest}
  %\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's first load the packages required.
```{r}
library(CDMConnector)
library(CohortSurvival)
library(dplyr)
library(ggplot2)
```

We'll create a cdm reference to use our example MGUS2 survival dataset. In practice you would use the CDMConnector package to connect to your data mapped to the OMOP CDM.
```{r}
cdm <- CohortSurvival::mockMGUS2cdm()
```

In this vignette we'll first estimate survival following a diagnosis of MGUS, with death our outcome of interest. 

We would typically need to define study cohorts ourselves, but in the case of our example data we already have these cohorts available. You can see for our diagnosis cohort we also have a number of additional features recorded for individuals which we'll use for stratification.

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

cdm$death_cohort %>% 
  glimpse()
```

## Overall survival
First, we can estimate survival for the cohort overall like so. Note that the output will be in a summarised result format.
```{r}
MGUS_death <- estimateSingleEventSurvival(cdm,
  targetCohortTable = "mgus_diagnosis",
  outcomeCohortTable = "death_cohort"
)
MGUS_death %>% 
  glimpse()
class(MGUS_death)
```

We can though convert the result to be in a survival format using asSurvivalResult()
```{r}
MGUS_death %>% 
  asSurvivalResult() %>%
  glimpse()
```

As we can see above our results have been outputted in long format. We can plot these results like so.
```{r}
plotSurvival(MGUS_death)
```

Our returned results also have attributes containing information that summarises survival. 
```{r}
tableSurvival(MGUS_death) 
```

## With stratification
To estimate survival for particular strata of interest we need these features to have been added to the target cohort table. Once we have them defined, and as seen above we already have a number of example characteristics added to our diagnosis cohort, we can add stratifications like so.
```{r}
MGUS_death <- estimateSingleEventSurvival(cdm,
  targetCohortTable = "mgus_diagnosis",
  outcomeCohortTable = "death_cohort",
  strata = list(c("age_group"),
                c("sex"),
                c("age_group", "sex"))
) 
```

As we can see as well as results for each strata, we'll always also have overall results returned.
```{r, fig.height=6, fig.width=8}
plotSurvival(MGUS_death,
             facet = "strata_name",
             colour = "strata_level")
```

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

```{r}
tableSurvival(MGUS_death)
```

## Disconnect from the cdm database connection
```{r}
cdmDisconnect(cdm)
```
