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

# 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 
`gather` 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 %>%
    rownames_to_column %>%
    select(rowname, cyl, gear, hp, mpg, qsec) %>%
    gather(per_metric, value, 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)) %>%
    gather(summary_stat, value, 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}
tidy_summary  %>% 
    tidyHtmlTable(header = "gear",
                 cgroup1 = "cyl",
                 cell_value = "value", 
                 rnames = "summary_stat",
                 rgroup = "per_metric")
```

### Example 2

```{r}
tidy_summary  %>% 
    tidyHtmlTable(header = "summary_stat",
                 cgroup1 = "per_metric",
                 cell_value = "value", 
                 rnames = "gear",
                 rgroup = "cyl")
```
