---
title: "Rmarkdown"
author: "Torben Tvedebrink"
output:
  html_document:
    df_print: paged
    code_folding: show
  word_document: default
  pdf_document: default
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
chunk <- "```"
inline <- function(x = "") paste0("`` `r ", x, "` ``")
```

# Computational essays

http://blog.stephenwolfram.com/2017/11/what-is-a-computational-essay/ 

There are basically three kinds of things [in a computational essay]:

* First, ordinary text (here in English). 
* Second, computer input. 
* And third, computer output. 

And the crucial point is that these three kinds of these all work together to express what’s being communicated.

# Rmarkdown

Interleaved R input and output together with your narative. In R we use Rmarkdown which combines [markdown](https://en.wikipedia.org/wiki/Markdown) with R input and rendered output. We can (depending on 
system install) output to html, pdf and MS Word files. This implies that we can make both static and dynamic
documents, including tables, pictures and mathematical formulae.

[R Markdown: The Definitive Guide](ttps://bookdown.org/yihui/rmarkdown/)

# Setup `knitr`

The first **chunk** called `setup` will specify the default behaviour for the remaining chunks in the documents.
There are _many_ parameters to tune: 

```{r knitr_opts, include = FALSE}
knitr::opts_chunk$get() %>% enframe() %>% 
  rowwise() %>% 
  mutate(value = ifelse(is.null(value), "NULL", paste(value))) %>% 
  unnest()
```

### Chunk options

The complete list is available at [Yihui Xie's webpage](https://yihui.name/knitr/options/#code-decoration)

The most relevant ones are (default first):

* `eval = TRUE/FALSE`: Evaluate the code? Can also be numeric, e.g. `eval = 1:3` only evaluates the first three
lines. This can also be negative, e.g. `eval = -2` skips line two.
* `include = TRUE/FALSE`: Should the *output* be included in the document?
* `echo = TRUE/FALSE`: Should the *input* be included in the document? Can also be numeric.
* `message = TRUE/FALSE`: Should messages be included?
* `warning = TRUE/FALSE`: Should warnings be included?
* `results = 'markup', 'asis', 'hold', 'hide'`. The `'hide'` options suppress te results and `'asis'` do not 
format the output.
* `error = FALSE/TRUE`: Should errors be allowed (i.e. should be continue on error?)


Option             | Run code | Show code | Output | Plots | Messages | Warnings 
-------------------|----------|-----------|--------|-------|----------|---------
`eval = FALSE`     | -        |           | -      | -     | -        | -
`include = FALSE`  |          | -         | -      | -     | -        | -
`echo = FALSE`     |          | -         |        |       |          |
`results = "hide"` |          |           | -      |       |          | 
`fig.show = "hide"`|          |           |        | -     |          |
`message = FALSE`  |          |           |        |       | -        |
`warning = FALSE`  |          |           |        |       |          | -

### Global options

    `r chunk`{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE, message = FALSE, comment = NA, 
                          fig.width = 10, warning = FALSE, error = TRUE)
    `r chunk`

By setting the above line in the beginning of the document, these values applies as default values for _all_ 
chunks in the document. However, all options can be overwritten locally.

### Inline code

When we want to format code in `tt`-font, we simply enclose it in ticks. If we want to output from R, 
we simply add a r in the beginning, e.g. `2+3 =` `r 2+3`

# This is a section header

## With a subsection below it

# markdown syntax

The syntax behind this document format is known as **markdown** - hence almost everything that works in markdown 
works in Rmarkdown. 

```{r markdown_syntax, echo = FALSE, comment = ""}
cat(readr::read_file("day-2-markdown.md"))
```

## How the process is done

![Rmarkdown flow](day-2-RmarkdownFlow.png) 

## YAML header

Yet Another Meta Language

```
---
title: "Rmarkdown"
author: "Torben"
date: "August 21, 2018"
output: html_document
---
```

# Formatting R objects for nice output

There are several such packages that extents `knitr` and `Rmarkdown`. One is `pander` (the engine converting
Rmarkdown to its output format is `pandoc`). It works 

```{r pander}
library(pander)
```

```{r tab}
tab <- data.frame(
  species = c("ex", "niv"), 
  mean_temp = c(25.7571428571429, 21.71875), 
  mean_pps = c(85.5857142857143, 61.0375))
```

```{r tab_print}
tab
```

```{r tab_pander}
pander(tab)
```


```{r pander_methods}
?pander
methods(pander)
```

* <https://cran.r-project.org/package=pander> 
* <https://cran.r-project.org/web/packages/pander/vignettes/pandoc_table.html>

```{r pandoc_table}
?pandoc.table
```


```{r pander_justify}
pander(tab, justify = c('right', 'center', 'left'))
```

```{r pander_font}
pander(tab, 
       justify = c('right', 'center', 'left'), 
       emphasize.strong.cols = 2)
```

```{r pander_digits}
pander(tab, digits = 5)
```

### Caching

Occationally we have parts of the code that takes very long time to run. E.g. when tuning parameters
in some data mining/machine learning algorithm it can take several hours. However, to allow such analysis
to be included in a Rmarkdown document, the `cache` option is available in Rmarkdown.

    `r chunk`{r raw_data}
    rawdata <- readr::read_csv("a_very_large_file.csv")
    `r chunk`
    
Where reading the file and process it subsequently could take a lot of time.

    `r chunk`{r processed_data, cache = TRUE}
    processed_data <- rawdata %>% 
      filter(!is.na(import_var)) %>% 
      mutate(new_variable = complicated_transformation(x, y, z))
    `r chunk`

Caching the processed_data chunk means that it will get re-run if the dplyr pipeline is changed, 
but it won’t get rerun if the `read_csv()` call changes (that is if the data changes!). 
You can avoid that problem with the `dependson` chunk option:

    `r chunk`{r processed_data, cache = TRUE, dependson = "raw_data"}
    processed_data <- rawdata %>% 
      filter(!is.na(import_var)) %>% 
      mutate(new_variable = complicated_transformation(x, y, z))
    `r chunk`

This example, and other, can highlight the importance of naming your chunks. A different example involves
appendix of code. That is, code you need in the beginning of your document, but you don't want it to jam 
up the narrative, but on the other hand it may be important to show the code later for other people.

### Appendixing

We achieve this by referring to the relevant chunk, here `"appendix"`.

    `r chunk`{r appendix_ref, ref.label="appendix", echo = FALSE}
    `r chunk`

And then in the end of the document we have the chunk named `appendix`

    `r chunk`{r appendix}
    some_very_complicated_function <- function(...){
       [...]
    }
    `r chunk`

# Knitr

## Going from Rmarkdown to R script (`purl`)

```{r purl, eval = FALSE}
knitr::purl("day-2-Rmarkdown_to_Rscript.Rmd", output = "day-2-Rmarkdown_to_Rscript_doc1.R") ## documentation = 1
knitr::purl("day-2-Rmarkdown_to_Rscript.Rmd", output = "day-2-Rmarkdown_to_Rscript_doc0.R", documentation = 0) ## only code - no comments
knitr::purl("day-2-Rmarkdown_to_Rscript.Rmd", output = "day-2-Rmarkdown_to_Rscript_doc2.R", documentation = 2) ## comments as roxygen comments
```

## Going from R script to Rmarkdown (`spin`)

```{r spin, eval = FALSE}
knitr::spin("day-2-Rscript_to_Rmarkdown.R", knit = FALSE)
```

# The `DT` package {.tabset}

The R package `DT` (https://rstudio.github.io/DT/) provides an R interface to the JavaScript library `DataTables`, 
which is extremely powerful for tabulating data (**in html**) 

```{r DT}
library(DT)
```

## DT

## Default

```{r DT_default}
mtcars %>% DT::datatable()
```

## Filtering

```{r DT_filter}
mtcars %>% 
  mutate(cyl = factor(cyl)) %>% 
  DT::datatable(filter = "top")
```

## Buttons

```{r DT_buttons}
mtcars %>% 
  DT::datatable(
    extensions = 'Buttons', options = list(
      dom = 'Bfrtip',
      buttons = c('copy', 'csv', 'excel', 'pdf', 'print')
    ),
    filter = "bottom"
  )
```

## Editable

```{r DT_edit}
mtcars %>% DT::datatable(editable = TRUE)
```

## Responsive (phone friendly)

```{r DT_responsive}
mtcars %>% 
  datatable(extensions = 'Responsive')
```

## Coloured cells

[For more see](https://rstudio.github.io/DT/functions.html)

```{r DT_colouring}
mtcars %>% 
  DT::datatable(options = list(pageLength = nrow(.), dom = "t")) %>% 
  formatStyle(
    'cyl',
    backgroundColor = styleEqual(c(4, 6, 8), c('green', 'yellow', 'red'))
  )
```

