---
title: "Summarise cohort overlap"
output: 
  html_document:
    pandoc_args: [
      "--number-offset=1,0"
      ]
    number_sections: yes
    toc: yes
vignette: >
  %\VignetteIndexEntry{summarise_cohort_overlap}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---
  
```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>", message = FALSE, warning = FALSE
)

CDMConnector::requireEunomia()
```
  
When creating multiple cohorts we might be interested in the overlap between them. That is, how many individuals appear in multiple cohorts. CohortCharacteristics provides functions to generate such estimates and then summarise these estimates in tables and plots.

To see how this works let's create a few medication cohorts with the Eunomia synthetic dataset.

```{r, message=FALSE, warning = FALSE}
library(duckdb)
library(CDMConnector)
library(dplyr, warn.conflicts = FALSE)
library(CodelistGenerator)
library(PatientProfiles)
library(CohortCharacteristics)

con <- dbConnect(duckdb(), dbdir = eunomiaDir())
cdm <- cdmFromCon(
  con = con, cdmSchem = "main", writeSchema = "main", cdmName = "Eunomia"
)

medsCs <- getDrugIngredientCodes(
  cdm = cdm,
  name = c(
    "acetaminophen",
    "morphine",
    "warfarin"
  )
)

cdm <- generateConceptCohortSet(
  cdm = cdm,
  name = "meds",
  conceptSet = medsCs,
  end = "event_end_date",
  limit = "all",
  overwrite = TRUE
)

settings(cdm$meds)
cohortCount(cdm$meds)
```

Now we have our cohorts we can summarise the overlap between them.

```{r}
medsOverlap <- cdm$meds |>
  summariseCohortOverlap()
medsOverlap |>
  glimpse()
```

We have table and plotting functions to help view our results.

```{r}
tableCohortOverlap(medsOverlap, uniqueCombinations = FALSE)
```

```{r}
plotCohortOverlap(medsOverlap, uniqueCombinations = FALSE)
```

As well as generating these estimates for cohorts overall, we can also obtain stratified estimates. In this example we'll add age groups to our cohort table, and then obtain estimates stratified by these groups.
```{r}
cdm$meds <- cdm$meds |>
  addAge(ageGroup = list(c(0, 49), c(50, 150))) |>
  compute(temporary = FALSE, name = "meds") |>
  newCohortTable()
medsOverlap <- cdm$meds |>
  summariseCohortOverlap(strata = list("age_group"))
```

As with our overall results, we can quickly create tables and figures to view our stratified results.
```{r}
tableCohortOverlap(medsOverlap, uniqueCombinations = FALSE)
```

```{r}
plotCohortOverlap(
  medsOverlap,
  y = c("cohort_name_reference", "cohort_name_comparator"),
  facet = c("age_group"),
  uniqueCombinations = TRUE
)
```
