---
title: "Literate Programming in R Markdown"
author: "David A. Selby"
date: "27 September 2016"
output:
  beamer_presentation:
    fig_caption: no
    includes:
      in_header: beamer/colours.tex
    template: beamer/template.tex
    theme: Boadilla
    toc: yes
shortinstitute: Statistics
institute: Department of Statistics, University of Warwick
self_contained: true
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```

# Literate Programming

## Motivation

> 1. Literate programming helps peers understand and replicate your results, find errors and suggest enhancements

> 2. "Literate programming produces better-quality programs" --- *Donald Knuth*

> 3. Literate programming saves time and effort, so you can spend more time:
>        - doing *real* research
>        - in the pub
    
## Effective communication

> “If you can't write clearly, you probably don't think nearly as well as you think you do.” --- Kurt Vonnegut

> "If it was hard to write, it should be hard to read."  
--- Computer programmers' proverb
    
## Commenting code

**What does this code do?**

```r
data(women)
plot(women)
fit <- lm(weight ~ height, data = women)
abline(fit)
```

## Commenting code

**With comments:**

```r
# Analysis of the 'women' dataset in R
data(women) # Load the data
plot(weight~height, data = women) # Make a scatter plot
fit <- lm(weight ~ height, data = women) # Fit linear model
abline(fit) # Add a line of best fit to the plot
```

## Literate Programming

> "Let us change our traditional attitude to the construction of programs: Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to humans what we want the computer to do."
>
> --- Donald Knuth

### Who will read your code?

(@) Your supervisor
(@) Collaborators
(@) Reviewers
(@) Future *you*

---

\small The *World Almanac and Book of Facts* (1975) includes a dataset of heights (in) and weights (lbs) of 15 American women aged 30--39. It is built into `R`:

```{r women_eg, echo = 1, fig.show = 'hide'}
data(women)
plot(weight~height, data = women)
fit <- lm(weight ~ height, data = women)
abline(fit)
```

As height increases, weight appears to increases (almost) linearly: every inch in height adds approximately `r round(coef(fit)[2], 2)` lbs. This was determined by fitting a simple linear regression model of weight against height:

```{r women_eg, eval = F, echo = 3}
```

The resulting least-squares regression line can be drawn on a scatter plot of height against weight. The fit looks quite good...

```{r women_eg, eval = F, echo = c(2, 4)}
```

---

```{r women_eg, fig.height = 6, fig.width = 8, fig.align = 'center', echo = FALSE}
```

# Markdown

## Markdown syntax

```
Here is some text in *italics*, in **bold** and `teletype`.  

Here is a new paragraph, a [link](www.google.com) and an
image:  
![Wally](wally.jpg)

* These are
* bullet points

> "To be, or not to be, that is the question."
^[*Hamlet*, Act III, Scene I]

1. And this is
1. a numbered
7. list
```

## Markdown output

Here is some text in *italics*, in **bold** and `teletype`.  

Here is a new paragraph, a [link](www.google.com) and an
image:  
![Wally](wally.jpg)

* These are
* bullet points

> "To be, or not to be, that is the question."
^[*Hamlet*, Act III, Scene I]

1. And this is
1. a numbered
7. list

## Markdown tables

```markdown
| Left              | Centre         | Right  |
| ----------------- |:--------------:| ------:|
| You can           | This text is   |    42  |
| use **Markdown**  | centre-aligned |   314  |
| *within* tables   |                |    37  |
```

**Output**

| Left              | Centre         | Right  |
| ----------------- |:--------------:| ------:|
| You can           | This text is   |    42  |
| use **Markdown**  | centre-aligned |   314  |
| *within* tables   |                |    37  |

## Markdown code chunks

``````markdown
To investigate the relationship between `height` and `weight`,
we fitted a *simple linear regression model*, as follows.

```r
model <- lm(weight ~ height, data = women)
summary(model)
plot(model) # Residual diagnostics
```
``````

**Output**

To investigate the relationship between `height` and `weight`,
we fitted a *simple linear regression model*, as follows.

```r
model <- lm(weight ~ height, data = women)
summary(model)
plot(model) # Residual diagnostics
```

## YAML headers

```markdown
---
title: "The name of my Markdown document"
author: "David A. Selby"
date: "27 September 2016"
output: pdf_document
---

(content)
```

YAML (yet another markup language) headers let you specify additional options before `render`ing your document


## Markdown: so what?

So far, Markdown is just a lightweight typesetting program.

How will this help you become more productive?

Introducing **_R_ Markdown**...

# R Markdown

## R Markdown

An ordinary Markdown code chunk:

``````r
```r
your R code goes here
```
``````

An R Markdown **R code** chunk:

``````r
```{r} `r ''`
your R code goes here
```
``````

## R Markdown

```{r inlinefn, echo = FALSE}
rinline <- function(code, in_chunk = FALSE) {
  # A function that prints in-line R markdown code
  # verbatim and does not evaluate it
    if(in_chunk) {
        sprintf('`r %s`', code)
    } else sprintf('``` `r %s` ```', code)
}
```

You can run R **in-line** with text as well. To add in-line R code, we use the syntax `r rinline('your_code_here')`. This will **evaluate and return the result** within the paragraph. For example:

```r
If we multiply 13 and 56 we get `r rinline('13 * 56', TRUE)`.
The date today is `r rinline('format(Sys.Date(), "%d %B %Y")', TRUE)`.
There are `r rinline('nrow(iris)', TRUE)` observations in the iris data set.
```

### Output

If we multiply 13 and 56 we get `r 13 * 56`.  
The date today is `r format(Sys.Date(), "%d %B %Y")`.  
There are `r nrow(iris)` observations in the iris data set.


## I heard you like code chunks...

![Xzibit](xzibit.png)

## Re-using code chunks

``````r
Yo dawg, check out this *cool* plot:

```{r chunk1, echo = FALSE}`r ''`
image(volcano, col = terrain.colors(20), labels = NULL)
```

Here is the code we used to make it!

```{r chunk2}`r ''`
```{r chunk1, eval = FALSE}`r ''`
```
``````

## Re-using code chunks (output)

Yo dawg, check out this *cool* plot:

```{r chunk1, echo = FALSE, out.height = '4cm', fig.align = 'center'}
image(volcano, col = terrain.colors(20), labels = NULL)
```

Here is the code we used to make it!

```{r chunk2}
```{r chunk1, eval = FALSE}
```

## Other programming languages^[Assuming they are installed and on your `PATH`]

**A Python code chunk**

``````markdown
```{python}`r ''`
x = ['To', 'be', 'or', 'not', 'to', 'be']
y = [i.upper() for i in x]
print(" ".join(y) + 5 * '?!')
```
``````

**Output**

```{python}
x = ['To', 'be', 'or', 'not', 'to', 'be']
y = [i.upper() for i in x]
print(" ".join(y) + 5 * '?!')
```

# Lazy, productive research

## Nobody need ever know!

- `knitr::kable` or `xtable::xtable` to auto-generate tables

- `echo = FALSE` to hide code in output

- `cache = TRUE` to save results that take a long time to run

- `output: word_document` to generate `.docx` files

- Set a `bibliography` in YAML, then cite:  
e.g. "As found by `[@fisher1931]`..."

## Another thing R Markdown is great for

**Presentations!**

## Outreach in R Markdown

[Jekyll](https://jekyllrb.com/)
: transforms Markdown into static websites and blogs

[GitHub Pages](https://pages.github.com/)
: serves and hosts Jekyll web sites for free

[`knitr-jekyll`](https://github.com/yihui/knitr-jekyll)
: Automatically knits R Markdown documents, builds them with Jekyll and serves them locally

## Write your entire thesis in R Markdown

\centering ![Bookdown](https://bookdown.org/yihui/bookdown/images/cover.png)

<http://www.bookdown.org>

## Links & further reading

Literate Programming
: Donald Knuth (1992)

R Markdown
: <http://rmarkdown.rstudio.com>

knitr
: <http://yihui.name/knitr>

R Markdown reference guide and cheat sheet
: <https://www.rstudio.com/resources/cheatsheets/>