---
title: "Getting started with the daoh package"
author: "David Cumin"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Getting started with the daoh package}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", fig.width = 7, fig.height = 4)
library(daoh)
```

## Overview

The `daoh` package  calculates
**Days Alive and Out of Hospital (DAOH)** from administrative
admission/discharge/mortality records.

The package supports three hospital-time algorithms and three approaches to
incorporating death, allowing direct comparison of results under different
methodological assumptions.

---

## Core formula

$$\text{DAOH} = \max\!\bigl(0,\; T - H - D\bigr)$$

where $T$ is the follow-up period (days), $H$ is total merged hospital
time, and $D$ is dead time, both clipped to $[t_0,\; t_0 + T]$.

---

## Example 1 — Day-stay: the 1-day difference

A patient admitted and discharged on the same calendar date contributes
**0 nights** (nights algorithm) but **1 day** (days algorithm).
This is the most common source of disagreement between the two approaches.

```{r example1}
ex <- load_example("daystay")
ex$events

# Nights: 0 nights in hospital -> DAOH = 30/30 = 100%
calc_daoh(ex$events, ex$index_dates, period = 30, method = "nights")

# Days: 1 day in hospital -> DAOH = 29/30 = 96.7%
calc_daoh(ex$events, ex$index_dates, period = 30, method = "days")
```

For a population with $N$ merged hospital episodes in the period:

$$H^{\text{days}} - H^{\text{nights}} \approx N_{\text{episodes}}$$

So the expected difference in DAOH (days − nights) equals the mean number
of distinct hospital episodes per patient.

---

## Example 2 — Death handling

A patient with four admissions who dies within the 30-day follow-up period.

```{r example2}
ex2 <- load_example("death")
ex2$events

# All seven variants
results <- expand.grid(
  method       = c("nights", "days", "exact"),
  death_method = c("midday", "midnight", "zero"),
  stringsAsFactors = FALSE
)

results$daoh <- mapply(function(m, dm) {
  calc_daoh(ex2$events, ex2$index_dates,
            period = 30, method = m, death_method = dm)$daoh
}, results$method, results$death_method)

results$daohPC <- round(100 * results$daoh / 30, 1)
print(results)
```

Note the wide range of DAOH values (0% to ~40%) depending on the method
chosen — underscoring the importance of explicit reporting.

---

## Example 3 — Population-level analysis

```{r example3_load}
pop <- load_example("population")
```

### Compare nights vs days

```{r example3_compare}
res_n <- calc_daoh(pop$events, pop$index_dates, period = 90, method = "nights")
res_d <- calc_daoh(pop$events, pop$index_dates, period = 90, method = "days")

# Summary statistics
cat("Nights: median DAOH% =", round(median(res_n$daohPC), 1), "\n")
cat("Days:   median DAOH% =", round(median(res_d$daohPC), 1), "\n")

# Difference ≈ number of episodes per patient
cat("Mean episodes (nights):", round(mean(res_n$n_episodes), 2), "\n")
cat("Mean difference in DAOH (nights - days):",
    round(mean(res_n$daoh - res_d$daoh), 3), "days\n")
```

### Bland-Altman analysis

```{r ba_plot}
ba <- bland_altman_daoh(res_n, res_d)
cat(sprintf("Mean difference: %.3f%%\n95%% LoA: %.3f%% to %.3f%%\n",
            ba$mean_diff, ba$loa_lower, ba$loa_upper))

plot_daoh_ba(ba, method_a = "Nights", method_b = "Days")
```

### Quartile reclassification

```{r reclassify}
rc <- daoh_reclassify(res_n, res_d, n_groups = 4)
cat(sprintf("%.1f%% of patients change quartile when switching nights → days\n",
            rc$pct_reclassified))
print(rc$confusion_matrix)
plot_daoh_reclassify(rc, method_a = "Nights", method_b = "Days")
```

### Distribution plot

```{r dist_plot}
plot_daoh_dist(res_n, title = "DAOH – Nights algorithm, 90-day period")
```

---

## Recommended reporting

1. **Nights algorithm** when exact timestamps are unavailable or unreliable.
2. **No death=0 weighting** — credits pre-death days and avoids distribution distortion.
3. Explicit reporting of algorithm, death handling, and follow-up period.
4. DAOH at **30 days** as the primary perioperative endpoint (StEP recommendation).
