---
title: "Get-Data-for-Population"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Get-Data-for-Population}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

## Vignette Build Datetime

```{r built}
message(paste0('Datetime: ',Sys.Date(),':',Sys.time()))
```

## Load Libraries

```{r setup, message=FALSE}
library(repfun)
library(dplyr)
library(kableExtra)
```

## Set Up the Reporting Environment

```{r envir}
tmpdr <- tempdir()
datdir <- file.path(gsub("\\","/",tmpdr,fixed=TRUE),"datdir")
dir.create(datdir,showWarnings=FALSE)
repfun::copydata(datdir)
repfun::rs_setup(D_POP="SAFFL",D_POPLBL="Safety",D_POPDATA=repfun::adsl, 
         D_SUBJID=c("STUDYID","USUBJID"), R_ADAMDATA=datdir)
repfun:::rfenv$G_POPDATA %>% dplyr::mutate(TRT01AN=ifelse(TRT01A=='Placebo',1,ifelse(TRT01A=='Xanomeline Low Dose',2,3)),
                     SAFFL=ifelse((row_number() %% 10) == 0,'N',SAFFL)) %>% 
              repfun::ru_labels(varlabels=list('TRT01AN'='Actual Treatment for Period 01 (n)',
                                       'SAFFL'='Safety Population Flag')) -> G_POPDATA
```

## Read in ADAE, Restrict to Population and Add Population Variables

```{r update}
adae <- repfun:::rfenv$adamdata$adae.rda() %>% dplyr::select(-c('SAFFL','TRT01A')) %>% 
  repfun::ru_getdata(G_POPDATA, c("STUDYID", "USUBJID"), 
             keeppopvars=c("TRT01AN", "TRT01A", "SAFFL")) %>%
 dplyr::select(STUDYID,USUBJID,AEBODSYS,AEDECOD,SAFFL,TRT01AN,TRT01A) %>% 
  dplyr::arrange(STUDYID,USUBJID,AEBODSYS,AEDECOD,SAFFL,TRT01AN,TRT01A)
```

## Display the Results for AE Body System and Preferred Term

```{r results}
lbls <- sapply(adae,function(x){attr(x,"label")})
knitr::kable(head(adae,10), col.names=paste(names(lbls),lbls,sep=": "), 
             caption = "Results of Restricting to Population and Adding Population Variables") 
```
