---
title: "GT Demo - Part 2 - more elaborate"
author: "John D. Smith"
date: "10/16/2020"
output: html_document
---

## Resources:

-   <https://blog.rstudio.com/2020/04/08/great-looking-tables-gt-0-2/>
-   <https://gt.rstudio.com/>
-   <https://gt.rstudio.com/reference/index.html>

## Load libraries

```{r}
suppressPackageStartupMessages(library(tidyverse))
library(gt)
```

This demo meanders from the outside and top of a table and works its way in. At the end we explore how to use the output.

![](img/gt_parts_of_a_table.svg)

# The tour

## Continue with `gtcars`

We'll use the `gtcars` data frame including cars from all countries.

```{r}
glimpse(gtcars)
```

`gt` interacts with `dplyr` groups in interesting ways.

```{r}
mileage <- gtcars %>% 
  group_by(year, ctry_origin, bdy_style) %>% 
  summarize(n = n(), hp_mean = mean(hp), mpg_h_mean = mean(mpg_h))
```

## `group_by` is a natural

The last variable in the `group_by` becomes a row label and the others are concatenated into a block label.

```{r}
t <- mileage %>%
  gt()
t
```

We'll use a simpler grouping in subsequent examples. Just passing a grouped data frame produces a table with a more complicated structure than an un-grouped data frame.

```{r}
mileage <- gtcars %>%
  group_by(ctry_origin, bdy_style) %>%
  summarize(n = n(),
            hp_mean = mean(hp),
            mpg_h_mean = mean(mpg_h))

t <- mileage %>%
  gt()
t
```

## A bestiary of functions to format columns

`gt` provides the following `fmt_` functions:

-   `fmt_currency()`
-   `fmt_date()`
-   `fmt_datetime()`
-   `fmt_markdown()`
-   `fmt_missing()`
-   `fmt_number()`
-   `fmt_passthrough()`
-   `fmt_percent()`
-   `fmt_scientific()`
-   `fmt_time()`

```{r}
t <-  t %>%
  fmt_number(vars(n, hp_mean, mpg_h_mean),
             decimals = 0)
t
```

## Many `cols_` functions to manipulate columns

-   `cols_align()`
-   `cols_hide()`
-   `cols_label()`
-   `cols_merge()`
-   `cols_merge_range()`
-   `cols_merge_uncert()`
-   `cols_move()`
-   `cols_move_to_end()`
-   `cols_move_to_start()`
-   `cols_width()`

Nice labels for columns, except that labeling the `group_by` seems to have no effect.

```{r}
t <- t %>%
  cols_label(
    bdy_style = "Style",
    hp_mean = html("Horse<br>Power<br>Mean"),
    mpg_h_mean = html("Highway<br>MPG<br>Mean"),
    n = html("Number<br>of<br>Models"),
    ctry_origin = "Country"
  )
t

```

-   `tab_footnote()`
-   `tab_header()`
-   `tab_options()`
-   `tab_row_group()`
-   `tab_source_note()`
-   `tab_spanner()`
-   `tab_spanner_delim()`
-   `tab_stubhead()`
-   `tab_style()`

The `tab_spanner()` function helps describe the table's contents, but doesn't improve the labeling of the grouping variable.

```{r}
t <- t %>% 
  tab_spanner(
    label = "Mean",
    columns = vars(
      hp_mean, mpg_h_mean)
  ) %>% 
  tab_spanner(
    label = "Count",
    columns = vars(n)
  ) %>% 
  cols_label(
    bdy_style = "Style",
    hp_mean = html("Horse<br>Power"),
    mpg_h_mean = html("Highway<br>MPG"),
    n = html("Models"),
    ctry_origin = "Country"
  ) 
t
```

## Footnotes

Explanatory footnotes on individual cells can be specified in several ways.

```{r}
t <- t %>% 
tab_footnote(
    footnote = "Highest horsepower group of all.",
    locations = cells_body(
      columns = vars(hp_mean),
      rows = hp_mean == max(hp_mean))
  ) 
t
```

Footnotes appear in order on the table, not in the order they are specified:

```{r}
t <- t %>% 
tab_footnote(
    footnote = "Best overall gas mileage.",
    locations = cells_body(
      columns = vars(mpg_h_mean),
      rows = mpg_h_mean == 27.5)
  ) 
t
```

## Saving a `gt` table

The HTML file that `gtsave()` generates is easy to copy and paste into a Google Doc. The supported file extensions / file types are: `.html`, `.png`, `pdf`, `.tex`, `.ltx`, `.rtf`. In my, the `.png` files are not very easy to work with.

```{r}
gtsave(t, "gtdemo_table.html")
```

Here is a problem that I have not solved. Formatting totals at the bottom of a table.

```{r}
tm <- mileage %>% 
  gt(groupname_col = vars("bdy_style")) %>% 
    tab_spanner(
    label = "Mean",
    columns = vars(
      hp_mean, mpg_h_mean)
  ) %>% 
  tab_spanner(
    label = "Count",
    columns = vars(n)
  ) %>% 
  cols_label(
    bdy_style = "Style",
    hp_mean = html("Horse<br>Power"),
    mpg_h_mean = html("Highway<br>MPG"),
    n = html("Models"),
    ctry_origin = "Country"
  ) %>% 
  summary_rows(groups = NULL, 
               columns = vars(n), 
               fns = list(sum = ~sum(.))) %>% 
               # formatter = fmt_number(.)) %>% 
fmt_number(vars(n, hp_mean, mpg_h_mean),
             decimals = 0)
tm
```

# More resources

Here are some more in-depth resources about tables and `gt` in particular:

-   Tom Mock ([\@thomas\_mock](https://twitter.com/thomas_mock)) presentation on [Beautiful Tables in R; gt and the grammar of tables](https://themockup.blog/static/slides/intro-tables.html#1).

-   [Table Talk](http://www.storytellingwithdata.com/blog/2020/10/27/table-talkhttp://www.storytellingwithdata.com/blog/2020/10/27/table-talk) - [Alex Velez](http://www.storytellingwithdata.com/blog?author=5d025ce5e4376c0001389069) IN [Data Viz Challenge](http://www.storytellingwithdata.com/blog?category=Data+Viz+Challenge), [SWD Challenge](http://www.storytellingwithdata.com/blog?category=SWDchallenge)

-   [Rstudio Community](https://community.rstudio.com/) - [Table Contest](https://community.rstudio.com/c/R-Markdown/tables/38) - an incredibly rich set of examples

-   New package [reactable](https://glin.github.io/reactable/) - see the examples for what's possible

-   Kable

-   Anybody else?
