---
title: "Reproducible Reports with Quarto Documents"
author: "Evan Carey, Rian DeFaccio , for BH Analytics LLC"
format: 
  html:
    toc: true
    toc-location: left
    embed-resources: true
theme: "../common/css/zephyr.scss"
---

```{r setup, include=FALSE}
knitr::opts_knit$set(warning = FALSE, message = FALSE)
knitr::opts_chunk$set(warning = FALSE, message = FALSE)
```

```{r}
# load libraries and adjust settings
library(tidyverse)
```

## Overview

------------------------------------------------------------------------

In this lesson we will go into deeper detail about using Quarto notebooks. We will cover:

-   Creating a standard Quarto document.
-   Understanding output options and the YAML.
-   Rendering the document from RStudio.
-   Markdown text commands.
-   Understanding R code chunks and options.
-   Creating a parameterized report.

## Quarto Overview

------------------------------------------------------------------------

Quarto is a way to use R to create reproducible reports that are dynamically or statically linked to the underlying data sets.

-   Using Quarto, you can render reports in HTML, Word, or even PDF formats.
-   Quarto is also capable of creating books, websites and even interactive dashboards.
-   We will then shift to producing Word document reports using Quarto. You can use the underlying styles in Word documents to control how the word reports look.
-   Finally, we will show how to implement parameterized reports by generating reports in a loop and passing in parameters.

There are a variety of in-depth resources about Quarto, but we recommend starting with the official documentation from Posit:

🌐 <https://quarto.org/>

### 🔍 Explore! Quarto Gallery

Go to the following site and find one or two examples of Quarto in action that inspire you!

🌐 <https://quarto.org/docs/gallery/>

Post your favorites in the **Zoom Chat ☞** .

## Markdown and R

------------------------------------------------------------------------

Quarto documents are a combination of the R programming language and the markdown language. Markdown is a very straightforward formatting language that enables anyone to author well-structured content. Instead of worrying about exactly what each document piece should look like, you can use markdown to write in plain text linking different types of your content to different formats.

We combine markdown code to generate the typeset report with actual R code to generate tables graphs and other results to combine for a fully reproducible report. You will need to understand basic markdown as well as implement all of the R code you have already learned.

The ability to work with Quarto documents comes by default with RStudio. A Quarto document has the *.qmd* file extension which stands for "Quarto Markdown".

### ✍️ Your Turn! Start Your First *.qmd* File

Quarto files end with the *.qmd* file extension.

Using RStudio, go ahead and click **File** ➡ **New File** ➡ **Quarto Document...** to generate your first Quarto file. See the settings below that we will use for our first document.

![](images/make_quarto.png){width="502"}

See below the three main sections of a Quarto document:

![](images/quarto_elements.png){width="750"}

A little bit about each of these elements:

-   **YAML ("YAML Ain't Markup Language"):** This is where the title, author, and other information you selected in the GUI went.
-   **Markdown:** This is plain text that gets formatted. This is where you tell your story and do the bulk of your writing.
-   **Code Chunks:** These are where you interactive with your data via a programming language of your choice. There are lots of languages you could use, and you could use more than one in a single Quarto document.

### ✍️ Your Turn! Render Your First .QMD

Examine your new file, then click the ➡️**Render** button in RStudio to render the file.

-   This will generate an HTML version of your report.
-   "Rendering" is the act of converting your *.qmd* file into some other type of output, like an HTML page.
-   You will need to save your *.qmd* file before it will render. Save your file to the *notebooks/* folder.

## Learning Markdown

The markdown text is very straightforward. Let's open the Rstudio help on this topic. Go to **Help** ➡ **Markdown Quick Reference**. This should open a help document in the **Help** pane of RStudio.

### ✍️ Your Turn! Mimic the Markdown

In your own Quarto file try to create a document that matches the image below. Start by deleting everything that was initially in the document below the YAML (the header). The solution can also be found at *notebooks/07a_An_Imaginary_World.qmd*

------------------------------------------------------------------------

![](images/dataropolis.png){width="550"}

If you need to brush up on your LATEX, here is a cheat sheet:

🌐 <https://users.dickinson.edu/~richesod/latex/latexcheatsheet.pdf>

------------------------------------------------------------------------

## R Code Chunks and Inline Code

------------------------------------------------------------------------

Of course the magic of Quarto is including both R code and the resulting figures and tables as well as the markdown code. You can include R code in these documents either by including it within a chunk or by including it in-line.

When you are inside of an Quarto document, you can press **ctrl + alt + i** to insert a new R code chunk. Alternatively, you can click the green insert button at the top of the document and select R as the language.

You can include inline R code by using a set of back-ticks. See the following image for how to add in-line R code:

![](images/inline_r_code.png){width="800"}

### ✍️ Your Turn! Add R Code

Add some R code to your document:

-   Add an R code chunk near the top of your document that loads the *data/dataropolis.csv* data set, then creates a summary using the `summary()` function.
-   Add an inline R code chunk that tells us how many rows are in the data set.
-   Add another R code chunk that creates a ggplot of some element of the data set.
-   Add a second level header `##` at the beginning of this new section called **Data About the City**

## R Code Chunk Options

------------------------------------------------------------------------

You can give each R code chunk it's own name by adding text after the `r` in the first line of the chunk. You don't have to though.

Either after the R, or after the name, you can put a comma then start listing out different code chunk options. Here are some common options:

-   `echo` - This controls whether or not the R code is included in the document.
-   `eval` - This controls whether or not the R code is evaluated!
-   `include` - This controls if the results are included in the document.
-   `message` - This controls if messages are passed through to the document. I usually set this to false!
-   `warning` - this controls if warnings are passed through to the document. I usually set this to false in the final document.
-   There are also a number of different figure options to control the size and other aspects of the figure output.

### ✍️ Your Turn! Adjust Code Chunk Options

You will need to adjust some R code chunk options in order to get output just like the image below. See how close you can get!

![](images/r_code_chunk_options.png){width="700"}

For your future reference, here are more details on the code chunk options:

🌐 <https://quarto.org/docs/computations/execution-options.html>

## Default Code Chunk Options

------------------------------------------------------------------------

You can also set R code chunk options at the top of the document in the first R code chunk. This is done with the `knitr::opts_chunk$set()` function. If you wanted to set your document to have the default of `echo=FALSE`, `messages=FALSE` and `warnings=FALSE`, you could include the following in your first R code chunk:

```         
knitr::opts_chunk$set(echo = FALSE,
                      message = FALSE, 
                      warning = FALSE)
```

## Working Directory in Quarto

------------------------------------------------------------------------

You cannot set the working directory in the middle of an Quarto file. This is bad practice and you'll get a warning. If you set the working directory in a code cell, the change will only persist temporarily.

The working directory is by default the same folder as the Quarto file. So if you want to specify a path, it must be relative to the current directory the file is in.

If you do want to change the root directory that the file is evaluated in, there is a chunk option called `root.dir` that allows you to do that.

There are actually two different similar functions for setting chunk options:

-   `knitr::opts_chunk$set(...)`: This controls the behavior of the code cells when you are working interactively.

-   `knitr::opts_knit$set(...)`: This controls the behavior of the code cells when you knit the document.

Here is what I might put at the top of a Quarto document, just below the YAML header:

```{{r setup}}
knitr::opts_knit$set(warning = FALSE,
                      message = FALSE,
                      root.dir = 'C:/Users/evancarey/Dropbox/Work')
knitr::opts_chunk$set(warning = FALSE,
                      message = FALSE,
                      root.dir = 'C:/Users/evancarey/Dropbox/Work')
```

## YAML Header Options

------------------------------------------------------------------------

We can further control the output by changing options in the YAML header. So far we have been working with the default `html_document`.

### ✍️ Your Turn! Update YAML

Update the YAML by adding in the following `html_document` parameters, then knit to see the result:

```         
---   
title: "test"   
author: "Evan"   
date: "2/26/2022"   
format: 
  html:
    toc: true
    toc-location: left
    embed-resources: true
---
```

To learn more about the YAML options, see the following documentation:

🌐<https://quarto.org/docs/output-formats/html-basics.html>

### ✍️ Your Turn! Knit to Word

This time try rendering your Quarto document into a Microsoft Word file. Use the following commands in the YAML header.

```         
---
format: 
  docx:
    toc: true
---
```

## Better Looking Tables

------------------------------------------------------------------------

The default R code console output does not look very good in an Quarto document.

For example, if you simply add these R commands to an R code chunk, you get console printed output:

```{r, eval=FALSE}
# print part of the dataframe
mtcars[1:4,1:3]
```

```{r}
# print a table
table(mtcars$cyl,mtcars$gear)
```

You can generate better looking HTML tables by using the `kable()` function from the `knitr` package.

```{r}
# print part of the dataframe
knitr::kable(mtcars[1:4, 1:4],
      digits = 0,                         # rounding
      caption = 'Table of data',          # add caption
      format.args = list(big.mark = ',')) # add comma formatting
```

Here are some additional resources for making tables in the context of Quarto:

🌐 **FlexTable:** <https://davidgohel.github.io/flextable/>

🌐 **Gt:** <https://gt.rstudio.com/>

🌐 **GtSummary:** <https://www.danieldsjoberg.com/gtsummary/>

✏️ **NOTE:** Not all table making packages work with all types of outputs. See the table below for the limitations of some of the various R packages for building tables.

![<https://www.danieldsjoberg.com/gtsummary/articles/rmarkdown.html>](images/table_software.png){width="400"}

## Parameterized Quarto Documents

------------------------------------------------------------------------

If you've ever felt that a large part of your job is to:

> "Report out the same handful of KPIs every day (or month, or quarter), aggregated to each relevant business unit and a handful of combined groups.”

Then parameterized Quarto documents will make you MUCH more efficient!

You can define parameters in the YAML header of a Quarto document as in the following example:

```         
params:
  clinic_name: "Starlight Medical Center"
```

In the previous YAML code we have set the default value of the `clinic_name` parameter to be "Starlight Medical Center".

Then you can reference those parameters throughout the report in your R code.

```{r eval=FALSE}
data %>%
  filter(ClinicName == params$clinic_name)
```

Finally, you can render your documents from either the command line interface (CLI) or through the `quarto` R package. Below we show an example of rendering a Quarto document using the R package.

```{r eval=FALSE}
quarto::quarto_render(
  input          = "test_report.qmd",
  output_format  = 'html',
  output_file    = "Another Hospital.html",
  execute_params = list(clinic_name = "Another Hospital")
)
```

**NOTE:** You do not need the `quarto` package to render Quarto documents in RStudio, just to interact in the way we did in the prior example.

Then, with a fairly simple for-loop you could iterate through the creation of many versions of your report. You would consider the .*qmd* file a **template** that gets re-used many times.

We have built a fairly simple Quarto report that utilizes parameters at `reports/test_report.qmd` and an R script at `r_files/parameterized_quarto.R` that shows how to render Quarto documents using the `quarto` package. Let's take a minute to walk through these examples.

## Conditional Content

------------------------------------------------------------------------

One final feature that extends the idea of report templates even further is that of **conditional content.** This is content that only gets included in a report under certain conditions. You would include some inline R code (outside of an R code cell) like what is shown below.

````         
`r if (current_clinic_type == "Primary Care") "::: {.content-hidden}"`

Some markdown that is seen only if clinic type is primary care.

```{r}
# some R code that is only run if clinic type is primary care
patient <- visits %>% filter(PatientID == some_id)
```

`r if (current_clinic_type == "Primary Care") ":::"`
````

In the previous example, `current_clinic_type` is an R variable that was defined at some earlier point in the Quarto document.

For clarity, what is happening here is that we are using a "fenced block." The `:::` symbol creates a fence and the `{.content-hidden}` tag is applied to all the content within the fence. We use the R `if` statement to determine when to print the fence and associated tag or not.

You can include both markdown and code cells inside of a fenced area.

We have a sample report that utilizes conditional content at `reports/test_report_conditional_content.qmd` and R code to render it at `r_files/parameterized_quarto.R`.

## Conclusion

------------------------------------------------------------------------

This wraps up our discussion of using Quarto for creating reproducible reports!
