---
title: "Exposure Duration Table"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Exposure Duration Table}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r}
library(metalite)
library(metalite.sl)
```

# Create Exposure Duration Table

The exposure duration analysis aims to provide table to summarize by each identified duration category.
The development of exposure duration analysis involves functions:

- `metalite::meta_adam`: build the metadata (`meta` object) for analysis.
- `prepare_exp_duration`: prepare analysis raw datasets.
- `format_exp_duration`: prepare analysis outdata with proper format.
- `rtf_exp_duration`: transfer (mock) output dataset to RTF table.

```{r, out.width = "100%", out.height = "400px", echo = FALSE, fig.align = "center"}
knitr::include_graphics("pdf/exp0duration.pdf")
```

## Build a metadata

There are two steps to build the metadata (`meta` object): process the ADaM dataset and save metadata for analysis and reporting.

Step1: ADEXSUM, the ADaM dataset for Drug Exposrue Summary Data, is utilized to:

- Sum up duration by STUDYID SITENUM USUBJID SUBJID APERIOD EXTRT ADOSEFRM PARAMCD.
- Subset the exposure data by `upcase(trim(left(paramcd))) = "TRTDUR"`.
- Get the exposure duration `adexsum$AVAL` for all participants.
- Assign duration category `adexsum$EXDURGR` i.e.">=1 day", ">=7 days",">=28 days", ">=12 weeks" and ">=24 weeks".

```{r}
adsl <- r2rtf::r2rtf_adsl
adexsum <- data.frame(USUBJID = adsl$USUBJID)
adexsum$TRTA <- factor(adsl$TRT01A,
  levels = c("Placebo", "Xanomeline Low Dose", "Xanomeline High Dose"),
  labels = c("Placebo", "Low Dose", "High Dose")
)

adexsum$APERIODC <- "Base"
adexsum$APERIOD <- 1

set.seed(123) # Set a seed for reproducibility
adexsum$AVAL <- sample(x = 0:(24 * 7), size = length(adexsum$USUBJID), replace = TRUE)
adexsum$EXDURGR <- "not treated"
adexsum$EXDURGR[adexsum$AVAL >= 1] <- ">=1 day"
adexsum$EXDURGR[adexsum$AVAL >= 7] <- ">=7 days"
adexsum$EXDURGR[adexsum$AVAL >= 28] <- ">=28 days"
adexsum$EXDURGR[adexsum$AVAL >= 12 * 7] <- ">=12 weeks"
adexsum$EXDURGR[adexsum$AVAL >= 24 * 7] <- ">=24 weeks"

adexsum$EXDURGR <- factor(adexsum$EXDURGR,
  levels = c("not treated", ">=1 day", ">=7 days", ">=28 days", ">=12 weeks", ">=24 weeks")
)
unique(adexsum$EXDURGR)
```

Step2: Save analysis plan and metadata(parameter and analysis) information, then build meta object.

```{r}
plan <- metalite::plan(
  analysis = "exp_dur", population = "apat",
  observation = "apat", parameter = "expdur"
)

meta <- metalite::meta_adam(
  population = adexsum,
  observation = adexsum
) |>
  metalite::define_plan(plan) |>
  metalite::define_population(
    name = "apat",
    group = "TRTA",
    subset = quote(APERIOD == 1 & AVAL > 0)
  ) |>
  metalite::define_parameter(
    name = "expdur",
    var = "AVAL",
    label = "Exposure Duration (Days)",
    vargroup = "EXDURGR"
  ) |>
  metalite::define_analysis(
    name = "exp_dur",
    title = "Summary of Exposure Duration",
    label = "exposure duration table"
  ) |>
  metalite::meta_build()
```

## Analysis preparation

The input of the function `prepare_exp_duration()` is a `meta` object created by the metalite package. The resulting output comprises a collection of raw datasets for analysis and reporting.

```{r}
outdata <- prepare_exp_duration(meta)
outdata
```

Number of participants in population

```{r}
outdata$n[, 1:5]
```

Number of participants in each duration category

```{r}
charn <- data.frame(outdata$char_n[1])
head(charn[, 1:5], 6)
```

Proportion of participants in each duration category

```{r}
charp <- data.frame(outdata$char_prop[1])
head(charp[, 1:5], 6)
```

Statistical summary of exposure duration for each treatment

```{r}
chars <- data.frame(outdata$char_n[1])
tail(chars[, 1:5], 8)
```

## Format output

`format_exp_duration` to prepare analysis dataset before generate RTF output

```{r}
tbl <- format_exp_duration(outdata, display_col = c("n", "prop", "total"))
head(tbl$tbl)
```


## Output as RTF

`rtf_exp_duration` to generate RTF output

```{r, warning=FALSE}
outdata <- format_exp_duration(outdata, display_col = c("n", "prop", "total")) |>
  rtf_exp_duration(
    source = "Source:  [CDISCpilot: adam-adexsum]",
    path_outdata = tempfile(fileext = ".Rdata"),
    path_outtable = "outtable/exp0duration.rtf"
  )
```

```{r, out.width = "100%", out.height = "400px", echo = FALSE, fig.align = "center"}
knitr::include_graphics("pdf/exp0duration.pdf")
```
