---
title: "AE Specification"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{AE Specification}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

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

## Overview

The objective of this tutorial is to generate a production-ready AE specification analyses.
It extends examples shown in the
[specific AE chapter](https://r4csr.org/tlf-ae-specific.html)
of the _R for Clinical Study Reports and Submission_ book.

The AE specification analysis entails the creation of tables that summarize
details of different types of adverse events.
To accomplish this using metalite.ae, three essential functions are required:

- `prepare_ae_specific()`: prepare analysis raw datasets.
- `format_ae_specific()`: prepare analysis (mock) outdata with proper format.
- `tlf_ae_specific()`: transfer (mock) output dataset to RTF table.

There are three optional functions to extend AE specification analysis.

- `extend_ae_specific_inference()`: add risk difference inference results based on M&N method.
- `extend_ae_specific_duration()`: add average duration of AE.
- `extend_ae_specific_events()`: add average number of AE events.

An example output:

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

## Example data

Within metalite.ae, we utilized the ADSL and ADAE datasets from the metalite
package to create an illustrative dataset.
The metadata structure remains consistent across all analysis examples
within metalite.ae.
Additional information can be accessed on the
[metalite package website](https://merck.github.io/metalite/articles/metalite.html).

```{r}
meta <- meta_ae_example()
```

<details>
<summary>Click to show the output</summary>
```{r}
meta
```
</details>

### Analysis preparation

The function  `prepare_ae_specific()` is used to create a dataset for
AE summary analysis by utilizing predefined keywords specified
in the example data `meta`.

The resulting output of the function is an `outdata` object, which comprises
a collection of raw datasets for analysis and reporting.

```{r, message = FALSE}
outdata <- prepare_ae_specific(
  meta,
  population = "apat",
  observation = "wk12",
  parameter = "rel"
)
```

```{r}
outdata
```

The resulting dataset contains frequently used statistics,
with variables indexed according to the order specified in `outdata$group`.

```{r}
outdata$group
```

The row is indexed according to the order of `outdata$name`.

```{r}
head(data.frame(outdata$order, outdata$name))
```

- `n_pop`: number of participants in population.

```{r}
outdata$n_pop
```

- `n`: number of subjects with AE.

```{r}
head(outdata$n)
```

- `prop`: proportion of subjects with AE.

```{r}
head(outdata$prop)
```

- `diff`: risk difference compared with the `reference_group`.

```{r}
head(outdata$diff)
```

## Format output

Once the raw analysis results are obtained,
the `format_ae_specific()` function can be employed to prepare the outdata,
ensuring its compatibility with production-ready RTF tables.

```{r}
tbl <- outdata |> format_ae_specific()
head(tbl$tbl)
```

### Additional statistics

By using the `display` argument,
we can choose specific statistics to include.
For instance, we have the option to incorporate the risk difference.

```{r}
tbl <- outdata |> format_ae_specific(display = c("n", "prop", "diff"))
head(tbl$tbl)
```

To perform advanced analysis, the `extend_ae_specific_inference()` function
is utilized.
For instance, we can incorporate a 95% confidence interval based on the
Miettinen and Nurminen (M&N) method.
Further information regarding the M&N method can be found in the
[rate compare vignette](https://merck.github.io/metalite.ae/articles/rate-compare.html).

```{r}
tbl <- outdata |>
  extend_ae_specific_inference() |>
  format_ae_specific(display = c("n", "prop", "diff", "diff_ci"))
head(tbl$tbl)
```

We can use `extend_ae_specific_duration()` to add average duration of AE.

```{r}
tbl <- outdata |>
  extend_ae_specific_duration(duration_var = "ADURN") |>
  format_ae_specific(display = c("n", "prop", "dur"))

head(tbl$tbl)
```

We can use `extend_ae_specific_events()` to add number of AE and/or average of it per subject.

```{r}
tbl <- outdata |>
  extend_ae_specific_events() |>
  format_ae_specific(display = c("n", "prop", "events_count", "events_avg"))

head(tbl$tbl)
```

We can use `filter_method` and `filter_criteria` parameters to filter information based on the specified criteria:

- `filter_method`: A character value to specify how to filter rows (by `count` or `percent`).
    - `count`: Filter based on participant count.
    - `percent`: Filter based on percent incidence.
- `filter_criteria`: A numeric value to display rows where at least one therapy group has:
    - a percent incidence or participant count greater than or equal to the specified value.
    - If `filter_method` is `percent`, the value should be between 0 and 100.
    - If `filter_method` is `count`, the value should be greater than 0.


```{r}
tbl <- outdata |>
  extend_ae_specific_events() |>
  format_ae_specific(
    display = c("n", "prop", "events_count", "events_avg"),
    filter_method = "percent",
    filter_criteria = 6
  )

head(tbl$tbl)
```
In results above, rows having any one of "prop_x" values are greater than 6 get kept in the output.


We can use `sort_order` and `sort_column` parameters to sort results based on the specified criteria:

- `sort_order` A character value to specify sorting order:
    - `alphabetical`: Sort by alphabetical order.
    - `count_des`: Sort by count in descending order.
    - `count_asc`: Sort by count in ascending order.
- `sort_column A` character value of `group` in `outdata` used to sort a table with.

```{r}
tbl <- outdata |>
  extend_ae_specific_events() |>
  format_ae_specific(
    display = c("n", "prop", "events_count", "events_avg"),
    sort_order = c("count_des"),
    sort_column = c("Placebo")
  )

head(tbl$tbl)
```

### Mock data preparation

The `mock` argument facilitates the creation of a mock table with ease.

Please note that the intention of the `mock` argument is not to provide
an all-encompassing mock table template.
Instead, it serves as a convenient method to assist users in generating
a mock table that closely resembles the desired output layout.
To develop a more versatile mock table generation tool, further efforts
are necessary.
This could potentially involve the creation of a dedicated mock table
generation package or similar solutions.

```{r}
tbl <- outdata |> format_ae_specific(mock = TRUE)
head(tbl$tbl)
```

## RTF tables

The last step is to prepare the RTF table using `tlf_ae_summary()`.

```{r}
outdata |>
  format_ae_specific() |>
  tlf_ae_specific(
    meddra_version = "24.0",
    source = "Source:  [CDISCpilot: adam-adsl; adae]",
    path_outtable = "rtf/ae0specific1.rtf"
  )
```

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

The `tlf_ae_specific()` function also provides some commonly used arguments
to customize the table.

```{r}
outdata |>
  format_ae_specific() |>
  tlf_ae_specific(
    meddra_version = "24.0",
    source = "Source:  [CDISCpilot: adam-adsl; adae]",
    col_rel_width = c(6, rep(1, 8)),
    text_font_size = 8,
    orientation = "landscape",
    path_outtable = "rtf/ae0specific2.rtf"
  )
```

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

The mock table can also be generated.

```{r}
outdata |>
  format_ae_specific(mock = TRUE) |>
  tlf_ae_specific(
    meddra_version = "24.0",
    source = "Source:  [CDISCpilot: adam-adsl; adae]",
    path_outtable = "rtf/mock_ae0specific1.rtf"
  )
```

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