---
title: "Scripted HTML"
author: "Tim Bergsma"
date: "`r Sys.Date()`"
output: 
  rmarkdown::html_vignette:
    toc: true
vignette: >
  %\VignetteIndexEntry{Scripted HTML}
  %\VignetteEncoding{UTF-8}
  %\VignetteEngine{knitr::rmarkdown}
editor_options: 
  chunk_output_type: console
---

The point of this exercise is to demonstrate flexible rendering of 
subscripts and superscripts.  We want to write expressions for 
column labels and units that are fairly readable as they are, and
yet can be easily rendered with equivalent results in 
plotmath, html, or pdf.

First we load some packages.

```{r include = FALSE}
knitr::opts_chunk$set(dpi = 600, out.width = '50%')
```

```{r, message = FALSE, warning = FALSE}
library(magrittr)
library(ggplot2)
library(tablet)
library(yamlet)
library(dplyr)
library(kableExtra)
```

We create some example data.

```{r}
x <- data.frame(
  time = 1:10, 
  work = (1:10)^1.5, 
  group = 1:2, 
  set = c(rep('delta',5), rep('gamma', 5))
)
x %<>% decorate('
 time: [ Time_cum.^alpha, h ]
 work: [ Work_total_obs\\n, kg*m^2/s^2 ]
 group: [ Group, [ Second\\nGroup^\\*: 2, First\\nGroup^#: 1 ]]
 set: [ Set, [ gamma, delta ]]
')
x %>% decorations
```

The label for column ```work``` has nested subscripts suggesting
$\sf{Work_{total_{obs}}}$. The label for column ```time``` suggests
$\sf{Time_{cum}{}^{\alpha}}$.  The dot closes the subscript to distinguish
this from $\sf{Time_{cum^{\alpha}}}$. Backslash-n requests a line break.


How does this look when we plot it?
```{r, fig.width = 4.43, fig.height = 2.77}
x %>% 
  resolve %>% 
  ggplot(aes(time, work, color = group, shape = set)) + 
  geom_point()
```

By default, we get verbatim labels and units as substitutes for column names.

Next, we use ```enscript()``` instead of ```resolve()``` to indicate 
that the labels should be understood as
potentially having subscripts and superscripts.
For this to work well, units should be constructed
using *, /, and ^ (even though the "units"
package supports other encodings).

```{r, , fig.width = 4.33, fig.height = 2.82}
x %>% 
  enscript %>% 
  ggplot(aes(time, work, color = group, shape = set)) + 
  facet_grid(~ group) +
  geom_point()
```

In the background, ```enscript()``` is writing __expression__ and __plotmath__ attributes
(consumed by ```ggplot()``` ) and __title__ attributes (consumed by ```tablet()``` ).
We illustrate the latter.

```{r}
x %>% 
  enscript %>% 
  group_by(group, set) %>%
  tablet %>%
  as_kable
```


In summary, we have decorated our data with labels and 
units containing markup for subscripts and superscripts.
If everything goes well, these render similarly 
in figures and tables.  They also render similarly in
html and pdf.  Please see the pdf version of this document.

