---
title: "AE Listing"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{AE Listing}
  %\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 adverse events (AE) listing.

The AE listing offers comprehensive information on the desired adverse events.
There are two essential functions for constructing AE listing tables with metalite.ae:

- `prepare_ae_listing()`: prepare AE listing datasets.
- `tlf_ae_listing()`: transfer output datasets to RTF files.

An example output:

```{r, out.width = "100%", out.height = "400px", echo = FALSE, fig.align = "center"}
knitr::include_graphics("pdf/ae0listing0ser0wk12.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_listing()` is used to create a dataset for
AE listing 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}
tbl <- prepare_ae_listing(
  meta,
  analysis = "ae_listing",
  population = "apat",
  observation = "wk12",
  parameter = "ser"
)
```

```{r}
head(tbl$tbl)
```

```{r}
head(tbl$col_name)
```

## RTF tables

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

```{r}
footnote <- c(
  "Related: Investigator-assessed relationship of the adverse event to study medication. Y = RELATED, N = NOT RELATED",
  "Action Taken: Discontinued = DRUG WITHDRAWN, Interrupted = DRUG INTERRUPTED, Reduced = DOSE REDUCED, Increased = DOSE INCREASED, None = DOSE NOT CHANGED, N/A = NOT APPLICABLE.",
  "Outcome: Resolved = RECOVERED/RESOLVED, Resolving = RECOVERING/RESOLVING, Sequelae = RECOVERED/RESOLVED WITH SEQUELAE, Not resolved = NOT RECOVERED/NOT RESOLVED.",
  "Adverse event terms are from MedDRA Version 25.0."
)
```

```{r}
tbl |> tlf_ae_listing(
  footnotes = footnote,
  orientation = "portrait",
  source = "Source:  [CDISCpilot: adam-adsl; adae]",
  analysis = "ae_listing", # Provide analysis type defined in meta$analysis
  path_outtable = "rtf/ae0listing0ser0wk12.rtf",
  path_outdata = NULL
)
```

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