---
title: "Using tidyHtmlTable"
author: "Stephen Gragg"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Using tidyHtmlTable}
  %\VignetteEncoding{UTF-8}
  %\VignetteEngine{knitr::rmarkdown}
editor_options: 
  chunk_output_type: console
---

# Introduction

`tidyHtmlTable` acts as a wrapper function for the `htmlTable`
function allowing columns to be mapped from the input data to specific htmlTable 
parameters in a manner similar to ggplot2.

# Some Examples

## Prepare Data

We'll begin by turning the `mtcars` data into a tidy dataset. The 
`pivot_longer` function is called to collect 3 performance metrics into a pair 
of key and value columns.

```{r, message=FALSE}
library(magrittr)
library(tidyr)
library(dplyr)
library(htmlTable)
library(tibble)

td <- mtcars %>%
  as_tibble(rownames = "rnames") %>% 
  pivot_longer(names_to = "per_metric", 
               cols = c(hp, mpg, qsec))
```

Now we will compute 4 summary statistics for each of the 3 performance metrics.
This will be further grouped by number of cylinders and gears.

```{r}
tidy_summary <- td %>%
  group_by(cyl, gear, per_metric) %>% 
  summarise(Mean = round(mean(value), 1),
            SD = round(sd(value), 1),
            Min = round(min(value), 1),
            Max = round(max(value), 1),
            .groups = 'drop') %>%
  pivot_longer(names_to = "summary_stat", 
               cols = c(Mean, SD, Min, Max)) %>% 
  ungroup() %>% 
  mutate(gear = paste(gear, "Gears"),
         cyl = paste(cyl, "Cylinders"))
```

At this point, we are ready to implement the `htmlTable` function.
Essentially, this constructs an html table using arguments similar to the 
`htmlTable` function. However, whereas `htmlTable` required the user to manually
arrange the data and specify the column groups, headers, row names, row-groups,
etc., each of these components of the table is mapped to a column within the
input data.

## Output html table

### Example 1

```{r, warning=FALSE}
tidy_summary  %>% 
  arrange(per_metric, summary_stat) %>% 
  addHtmlTableStyle(align = "r") %>% 
  tidyHtmlTable(header = gear,
                cgroup = cyl,
                rnames = summary_stat,
                rgroup = per_metric)
```

### Example 2

```{r, warning=FALSE}
tidy_summary  %>% 
  arrange(cyl, gear) %>% 
  addHtmlTableStyle(align = "r") %>% 
  tidyHtmlTable(header = summary_stat,
                cgroup = per_metric,
                rnames = gear,
                rgroup = cyl)
```
