+ - 0:00:00
Notes for current slide
Notes for next slide

Advanced R for Econometricians

Reproducible Research with R Markdown

Martin C. Arnold, Jens Klenke

1 / 37

R Markdown

R Markdown provides a framework for combining code, results, and commentary.

You can use R Markdown

  • to generate reports, articles, books ...
  • as an environment in which to do data science, as a lab notebook where you can capture not only what you did, but also what you were thinking.
2 / 37

R Markdown

R Markdown provides a framework for combining code, results, and commentary.

You can use R Markdown

  • to generate reports, articles, books ...
  • as an environment in which to do data science, as a lab notebook where you can capture not only what you did, but also what you were thinking.

Some interesting links:

2 / 37

R Markdown

R Markdown provides a framework for combining code, results, and commentary.

You can use R Markdown

  • to generate reports, articles, books ...
  • as an environment in which to do data science, as a lab notebook where you can capture not only what you did, but also what you were thinking.

Some interesting links:

Example:

2 / 37

What’s possible with R Markdown?

3 / 37

Basic example

Example

---
title: "Diamond sizes"
date: 2016-08-25
output: html_document
---
```{r, include=FALSE}
library(tidyverse)
data("diamonds")
smaller <- diamonds %>%
filter(carat < 2.5)
```
We have data about `r nrow(diamonds)` diamonds. Only
`r nrow(diamonds) - nrow(smaller)` are **larger** than
2.5 *carats*. The distribution of the remainder is shown
below:
```{r, echo = FALSE}
smaller %>%
ggplot(aes(carat)) +
geom_freqpoly(binwidth = 0.01)
```
If $\frac{\alpha}{\beta} = \gamma$ then $\alpha = \gamma\beta$.
4 / 37

Basic example

Example

---
title: "Diamond sizes"
date: 2016-08-25
output: html_document
---
```{r, include=FALSE}
library(tidyverse)
data("diamonds")
smaller <- diamonds %>%
filter(carat < 2.5)
```
We have data about `r nrow(diamonds)` diamonds. Only
`r nrow(diamonds) - nrow(smaller)` are **larger** than
2.5 *carats*. The distribution of the remainder is shown
below:
```{r, echo = FALSE}
smaller %>%
ggplot(aes(carat)) +
geom_freqpoly(binwidth = 0.01)
```
If $\frac{\alpha}{\beta} = \gamma$ then $\alpha = \gamma\beta$.
  • If this is stored as example.rmd in your working directory run knitr::render(example.rmd) to create an output document.
  • Alternatively, hit the button in Rstudio.
  • Or you can use the short key combination Ctrl + Shift + K
4 / 37

How it works


An R Markdown document is a basic text file, with the (conventional) extension .Rmd.

The example already contains the most important components:

  • An (optional) YAML header surrounded by ---
  • Chunks of R code surrounded by ```{r, ...} and ```
  • Inline R code surrounded by `r and `
  • Text mixed with simple text formatting like bold and italics
  • Mathematical expressions
5 / 37

How it works


When we click knit in RStudio then

  1. the knitr package executes the code chunks and creates a markdown document (.md) which contains the text we have written and optionally the code and its output
  2. the .md file gets processed by pandoc which creates the final file in the desired output format (e.g. html, pdf, word, ...)


6 / 37

The YAML header

The YAML header contains settings passed to pandoc and the rendering functions. Here you can:

  • specify the output format with optional output specific options
  • provide information for the title page such as title, name, and date
  • include external files (e.g. .css) or additional packages for LATEX
  • define parameters.
7 / 37

The YAML header

The YAML header contains settings passed to pandoc and the rendering functions. Here you can:

  • specify the output format with optional output specific options
  • provide information for the title page such as title, name, and date
  • include external files (e.g. .css) or additional packages for LATEX
  • define parameters.

Example: Basic YAML header using mostly defaults

---
title: Habits
author: John Doe
date: March 22, 2005
output: html_document
---
7 / 37

YAML Ain't Markup Language, a recursive acronym, to distinguish its purpose as data-oriented, rather than document markup.

The YAML header

Example: A more complicated YAML header

---
title: Habits
author: John Doe
date: March 22, 2005
output:
html_document:
toc: true
toc_float:
collapsed: false
smooth_scroll: false
css: my_style.css
params:
pi: 3.141593
---
8 / 37

Output Formats


Learn more about further output formats at https://rmarkdown.rstudio.com.

9 / 37

Text Formatting

  • R Markdown is built on Pandoc Markdown, which in turn is a flavour of the markup language Markdown.
  • The advantage of Markdown compared to other markup languages such as HTML and LATEX is its simplicity.
10 / 37

Text Formatting

Example: Headers

# Header 1
## Header 2
### Header 3

Header 1

Header 2

Header 3

11 / 37

Text Formatting

Example: Headers

# Header 1
## Header 2
### Header 3

Header 1

Header 2

Header 3

Inline formatting

*italics*
**bold**
This ~~is deleted text.~~
Some code: `lm(y ~ x)`.
italics
bold
This is deleted text.
Some code: lm(y ~ x).

11 / 37

Text Formatting

Unordered Lists

* Item
- Item belonging to item
- Another item belonging to item
* Item
* Item
  • Item
    • Item belonging to item
    • Another item belonging to item
  • Item
  • Item
12 / 37

Text Formatting

Unordered Lists

* Item
- Item belonging to item
- Another item belonging to item
* Item
* Item
  • Item
    • Item belonging to item
    • Another item belonging to item
  • Item
  • Item

Ordered Lists

1. First item
- First subitem
- Second subitem
2. Second item
3. Third item
  1. First item
    • First subitem
    • Second subitem
  2. Second item
  3. Third item
12 / 37

Text Formatting

Unordered Lists

* Item
- Item belonging to item
- Another item belonging to item
* Item
* Item
  • Item
    • Item belonging to item
    • Another item belonging to item
  • Item
  • Item

Ordered Lists

1. First item
- First subitem
- Second subitem
2. Second item
3. Third item
  1. First item
    • First subitem
    • Second subitem
  2. Second item
  3. Third item

Note: Markdown does not support nested ordered lists with numbering 1.1, 1.2.1 and so on. For this, you would have to fall back to HTML or LATEX.

12 / 37

Text Formatting


Linebreaks

First line
Second line

First line
Second line



A new line is started by two whitespaces at the end of the previous line (which you cannot see here).

13 / 37

Text Formatting


Linebreaks

First line
Second line

First line
Second line



A new line is started by two whitespaces at the end of the previous line (which you cannot see here).

Paragraphs

First paragraph
Second paragraph

First paragraph

Second paragraph


A new paragraph is started by a blank line.

13 / 37

Math Expressions

When rendering to a pdf LATEX can be used throughout the document.
Through MathJax the LATEX math mode can also be used for HTML output as follows:

14 / 37

Math Expressions

When rendering to a pdf LATEX can be used throughout the document.
Through MathJax the LATEX math mode can also be used for HTML output as follows:

  • Inline LATEX equations can be written within dollar signs.
This is an inline equation $f(x)=\frac{1}{\sqrt{2\pi}}\exp{\left(-\frac{1}{2}x^2\right)}$.

This is an inline equation f(x)=12πexp(12x2).

14 / 37

Math Expressions

When rendering to a pdf LATEX can be used throughout the document.
Through MathJax the LATEX math mode can also be used for HTML output as follows:

  • Inline LATEX equations can be written within dollar signs.
This is an inline equation $f(x)=\frac{1}{\sqrt{2\pi}}\exp{\left(-\frac{1}{2}x^2\right)}$.

This is an inline equation f(x)=12πexp(12x2).

  • Display style LATEX equations can be written within double dollar signs.
This is display style $$f(x)=\frac{1}{\sqrt{2\pi}}\exp{\left(-\frac{1}{2}x^2\right)}$$.

This is display style f(x)=12πexp(12x2)

14 / 37

Math Expressions

  • Even more complex math environments such as align can be used

Example

\begin{align}
(a+b)^{3} &=(a+b)(a+b)^{2} \\
&=(a+b)\left(a^{2}+2 a b+b^{2}\right) \\
&=a^{3}+3 a^{2} b+3 a b^{2}+b^{3}
\end{align}


15 / 37

Math Expressions

  • Even more complex math environments such as align can be used

Example

\begin{align}
(a+b)^{3} &=(a+b)(a+b)^{2} \\
&=(a+b)\left(a^{2}+2 a b+b^{2}\right) \\
&=a^{3}+3 a^{2} b+3 a b^{2}+b^{3}
\end{align}


(1)(a+b)3=(a+b)(a+b)2(2)=(a+b)(a2+2ab+b2)(3)=a3+3a2b+3ab2+b3

15 / 37

Code Chunks

  • You can write arbitrary R code in a code chunk (e.g. run a regression and produce a plot of the result).
  • The code, the result of the code or both can be included into the final document.
  • In the top curly braces, chunk options can be set to control how the output is handled.
16 / 37

Code Chunks

  • You can write arbitrary R code in a code chunk (e.g. run a regression and produce a plot of the result).
  • The code, the result of the code or both can be included into the final document.
  • In the top curly braces, chunk options can be set to control how the output is handled.

Some useful options:

  • eval(TRUE; logical): whether to evaluate the code chunk
  • echo(TRUE; logical or numeric): whether to include R source code in the output file
  • cache(FALSE; logical): whether to cache a code chunk
  • warning (TRUE; logical): whether to preserve warnings
  • message (TRUE; logical): whether to preserve messages
  • include (TRUE; logical): whether to include the chunk output in the final output document
16 / 37

Code Chunks

  • You can write arbitrary R code in a code chunk (e.g. run a regression and produce a plot of the result).
  • The code, the result of the code or both can be included into the final document.
  • In the top curly braces, chunk options can be set to control how the output is handled.

Some useful options:

  • eval(TRUE; logical): whether to evaluate the code chunk
  • echo(TRUE; logical or numeric): whether to include R source code in the output file
  • cache(FALSE; logical): whether to cache a code chunk
  • warning (TRUE; logical): whether to preserve warnings
  • message (TRUE; logical): whether to preserve messages
  • include (TRUE; logical): whether to include the chunk output in the final output document

For a complete list, we refer to the knitr documentation: Chunk options.

16 / 37

Code Chunks

  • You can write arbitrary R code in a code chunk (e.g. run a regression and produce a plot of the result).
  • The code, the result of the code or both can be included into the final document.
  • In the top curly braces, chunk options can be set to control how the output is handled.

Some useful options:

  • eval(TRUE; logical): whether to evaluate the code chunk
  • echo(TRUE; logical or numeric): whether to include R source code in the output file
  • cache(FALSE; logical): whether to cache a code chunk
  • warning (TRUE; logical): whether to preserve warnings
  • message (TRUE; logical): whether to preserve messages
  • include (TRUE; logical): whether to include the chunk output in the final output document

For a complete list, we refer to the knitr documentation: Chunk options.

  • Press Ctrl + Alt + I to insert a new R code chunk.
16 / 37

Code Chunks

Example

```{r lin_reg, echo=TRUE, cache = TRUE}
x <- runif(100)
y <- 0.4 * x + rnorm(100)
lm(y ~ x)
```
17 / 37

Code Chunks

Example

```{r lin_reg, echo=TRUE, cache = TRUE}
x <- runif(100)
y <- 0.4 * x + rnorm(100)
lm(y ~ x)
```


If you mainly use chunk options which are not the default, then it saves time to change the default for the document with knitr::opts_chunk$set().

Example: chunk setup

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo=FALSE, warning=FALSE, message=FALSE)
```
17 / 37

Inline R Code

You can also use R in your running text. When something changes (e.g. the input data) the numbers in the text adjust accordingly as well.

Example

```{r, echo=FALSE}
x <- 4
y <- 38
answer <- x + y
```
The answer is `r answer`
18 / 37

Inline R Code

You can also use R in your running text. When something changes (e.g. the input data) the numbers in the text adjust accordingly as well.

Example

```{r, echo=FALSE}
x <- 4
y <- 38
answer <- x + y
```
The answer is `r answer`

The answer is 42.

18 / 37

Tables

Tables can be created as follows:

Example

| Right | Left | Default | Center |
|------:|:-----|---------|:------:|
| 12 | 12 | 12 | 12 |
| 123 | 123 | 123 | 123 |
| 1 | 1 | 1 | 1 |
19 / 37

Tables

Tables can be created as follows:

Example

| Right | Left | Default | Center |
|------:|:-----|---------|:------:|
| 12 | 12 | 12 | 12 |
| 123 | 123 | 123 | 123 |
| 1 | 1 | 1 | 1 |



Right Left Default Center
12 12 12 12
123 123 123 123
1 1 1 1
19 / 37

Tables

Tables can be created as follows:

Example

| Right | Left | Default | Center |
|------:|:-----|---------|:------:|
| 12 | 12 | 12 | 12 |
| 123 | 123 | 123 | 123 |
| 1 | 1 | 1 | 1 |



Right Left Default Center
12 12 12 12
123 123 123 123
1 1 1 1


In general, however, tables should be produced by your code. The following slides show some examples.

19 / 37

kable

  • knitr::kable() is probably the easiest way to transform a matrix or a data frame into a table.

Example

```{r}
result <- data.frame(rbind(rep(12,4), rep(123, 4), rep(1,4)))
names(result) <- c("Right", "Left", "Default", "Center")
knitr::kable(result, align = c("r", "l", "l", "c"), format = "html")
```
20 / 37

kable

  • knitr::kable() is probably the easiest way to transform a matrix or a data frame into a table.

Example

```{r}
result <- data.frame(rbind(rep(12,4), rep(123, 4), rep(1,4)))
names(result) <- c("Right", "Left", "Default", "Center")
knitr::kable(result, align = c("r", "l", "l", "c"), format = "html")
```


Right Left Default Center
12 12 12 12
123 123 123 123
1 1 1 1
20 / 37

kableExtra

  • The appearance of a table (not only produced by knitr::kable()) depends on the underlying css (in case of an HTML document) or the generated LATEX code.
  • The package kableExtra allows to format your knitr::kable() table without the use of css or LATEX
21 / 37

kableExtra

  • The appearance of a table (not only produced by knitr::kable()) depends on the underlying css (in case of an HTML document) or the generated LATEX code.
  • The package kableExtra allows to format your knitr::kable() table without the use of css or LATEX

Example

```{r}
library(magrittr)
library(kableExtra)
knitr::kable(result,
align = c("r", "l", "l", "c"),
format = "html") %>%
kableExtra::kable_styling(bootstrap_options = "bordered")
```
21 / 37

kableExtra

  • The appearance of a table (not only produced by knitr::kable()) depends on the underlying css (in case of an HTML document) or the generated LATEX code.
  • The package kableExtra allows to format your knitr::kable() table without the use of css or LATEX

Example

```{r}
library(magrittr)
library(kableExtra)
knitr::kable(result,
align = c("r", "l", "l", "c"),
format = "html") %>%
kableExtra::kable_styling(bootstrap_options = "bordered")
```
21 / 37

xtable

  • xtable provides more functionality than kable but is a bit more difficult to use.
  • If your code produces raw HTML or LATEX e.g. for a table then you have to set results='asis' in the chunk options, otherwise it gets formatted and will not work as intended.
22 / 37

xtable

  • xtable provides more functionality than kable but is a bit more difficult to use.
  • If your code produces raw HTML or LATEX e.g. for a table then you have to set results='asis' in the chunk options, otherwise it gets formatted and will not work as intended.

Example

```{r, echo=FALSE, results='asis'}
library(xtable)
my_xtable <- xtable(result, align = c("r", "r", "l", "l", "c"))
print.xtable(my_xtable, type = "html", include.rownames = FALSE)
```
22 / 37

xtable

  • xtable provides more functionality than kable but is a bit more difficult to use.
  • If your code produces raw HTML or LATEX e.g. for a table then you have to set results='asis' in the chunk options, otherwise it gets formatted and will not work as intended.

Example

```{r, echo=FALSE, results='asis'}
library(xtable)
my_xtable <- xtable(result, align = c("r", "r", "l", "l", "c"))
print.xtable(my_xtable, type = "html", include.rownames = FALSE)
```

Right Left Default Center
12.00 12.00 12.00 12.00
123.00 123.00 123.00 123.00
1.00 1.00 1.00 1.00
22 / 37

stargazer

  • stargazer takes model objects as input and automatically creates an output table


Example

```{r, results='asis', echo=TRUE}
linear_model <- lm(mpg ~ cyl + wt,
data = mtcars)
stargazer::stargazer(linear_model,
type = "html",
out.header = TRUE,
omit.table.layout = "sn")
```
23 / 37

stargazer

  • stargazer takes model objects as input and automatically creates an output table


Example

```{r, results='asis', echo=TRUE}
linear_model <- lm(mpg ~ cyl + wt,
data = mtcars)
stargazer::stargazer(linear_model,
type = "html",
out.header = TRUE,
omit.table.layout = "sn")
```
Dependent variable:
mpg
cyl-1.508***
(0.415)
wt-3.191***
(0.757)
Constant39.686***
(1.715)
23 / 37

Plots


Example

```{r, fig.height = 5}
hist(rnorm(1000))
```
24 / 37

Plots


Example

```{r, fig.height = 5}
hist(rnorm(1000))
```

24 / 37
  • Links can be created as follows:
[This is a link to the R Markdown book](https://bookdown.org/yihui/rmarkdown/)
25 / 37
  • Links can be created as follows:
[This is a link to the R Markdown book](https://bookdown.org/yihui/rmarkdown/)
  • To include figures saved on your computer use
![Figure Description](path/to/figure.png)
25 / 37
  • Links can be created as follows:
[This is a link to the R Markdown book](https://bookdown.org/yihui/rmarkdown/)
  • To include figures saved on your computer use
![Figure Description](path/to/figure.png)
  • If you need more control over the appearence of the figure you can use
```{r, out.width = "500px", fig.align='center'}
knitr::include_graphics("path/to/figure.png")
```
25 / 37

Using HTML and LATEX

  • If only R Markdown is used the document can be compiled without problems to all supported output formats.

  • Sometimes R Markdown is too limited and one would like to use the more powerful tools provided by HTML or LATEX.

  • If the output format is HTML, you can also use HTML instead of R Markdown or mix both.

  • If the output format is PDF, the same can be said about LATEX

26 / 37

Interactive documents

  • If the output is HTML, interactive elements (usually some JavaScript) can be included.
  • There are R packages producing interactive output e.g. plotly for interactive plots or leaflet for interactive maps.
27 / 37

Interactive documents

  • If the output is HTML, interactive elements (usually some JavaScript) can be included.
  • There are R packages producing interactive output e.g. plotly for interactive plots or leaflet for interactive maps.

Example: plot

```{r}
library(plotly)
mtcars$am[which(mtcars$am == 0)] <- 'Automatic'
mtcars$am[which(mtcars$am == 1)] <- 'Manual'
mtcars$am <- as.factor(mtcars$am)
plot_ly(mtcars, x = ~wt, y = ~hp, z = ~qsec, color = ~am, colors = c('#BF382A', '#0C4B8E')) %>%
add_markers() %>%
layout(scene = list(xaxis = list(title = 'Weight'),
yaxis = list(title = 'Gross horsepower'),
zaxis = list(title = '1/4 mile time')))
```
27 / 37

Interactive documents

28 / 37

Interactive documents

Example: map

```{r, out.width='100%'}
library(leaflet)
leaflet() %>% addTiles() %>%
setView(7.005070, 51.463675,zoom = 17) %>%
addMarkers(
7.005070, 51.463675
)
```
29 / 37

Interactive documents

Example: map

```{r, out.width='100%'}
library(leaflet)
leaflet() %>% addTiles() %>%
setView(7.005070, 51.463675,zoom = 17) %>%
addMarkers(
7.005070, 51.463675
)
```
29 / 37

Interactive documents

  • The DT package also allows us to include interactive tables.

Example: map

```{r}
DT::datatable( head(iris, 10),
fillContainer = TRUE, options = list(pageLength = 5))
```
30 / 37

Interactive documents

  • The DT package also allows us to include interactive tables.

Example: map

```{r}
DT::datatable( head(iris, 10),
fillContainer = TRUE, options = list(pageLength = 5))
```


30 / 37

Advanced Topics: Hooks

  • You can define your own chunk options using hooks. This is a topic for you if you want to become a professional knitr user.
31 / 37

Advanced Topics: Hooks

  • You can define your own chunk options using hooks. This is a topic for you if you want to become a professional knitr user.

Chunk Hooks

  • A chunk hook is a function defining what should happen before or after a code chunk.
# Template for a chunk hook
knitr::knit_hooks$set(
foo_hook = function(before, options, envir) {
if (before) {
## code to be run before a chunk
} else {
## code to be run after a chunk
}
})
31 / 37

Advanced Topics: Hooks

  • You can define your own chunk options using hooks. This is a topic for you if you want to become a professional knitr user.

Chunk Hooks

  • A chunk hook is a function defining what should happen before or after a code chunk.
# Template for a chunk hook
knitr::knit_hooks$set(
foo_hook = function(before, options, envir) {
if (before) {
## code to be run before a chunk
} else {
## code to be run after a chunk
}
})
  • Before the chunk is evaluated the function is called with before == TRUE
    and after with before == FALSE.
  • options is a list with the current chunk options (optional).
  • envir is the enviornment in which the the code chunk is evaluated (optional).
31 / 37

Chunk Hooks: Example

  • To reduce the margins of a plot with chunk option small.mar = TRUE put the following code chunk at the top of your document.

Function

```{r, eval = FALSE, echo=TRUE}
knitr::knit_hooks$set(small.mar = function(before) {
if (before) par(mar = c(1, 1, 1, 1))
})
```
32 / 37

Chunk Hooks: Example

  • To reduce the margins of a plot with chunk option small.mar = TRUE put the following code chunk at the top of your document.

Function

```{r, eval = FALSE, echo=TRUE}
knitr::knit_hooks$set(small.mar = function(before) {
if (before) par(mar = c(1, 1, 1, 1))
})
```
  • small.mar now can be used as other chunk options.

Example

```{r, small.mar = TRUE}
hist(rnorm)
```
32 / 37

Output Hooks

  • Output hooks are (render) functions that define how source code and its output is presented.
  • There are 8 output hooks to deal with differnt types of output:
    • source: the source code
    • output: what would have been printed in an R terminal except warnings, messages and errors.
    • warnings: warnings from warning()
    • message: messages from message()
    • error: errors from stop()
    • plot: graphics output
    • inline: output of inline R code
    • chunk: all the output of a chunk
    • document: the output of the whole document
33 / 37

Output Hooks

  • Output hooks are (render) functions that define how source code and its output is presented.
  • There are 8 output hooks to deal with differnt types of output:
    • source: the source code
    • output: what would have been printed in an R terminal except warnings, messages and errors.
    • warnings: warnings from warning()
    • message: messages from message()
    • error: errors from stop()
    • plot: graphics output
    • inline: output of inline R code
    • chunk: all the output of a chunk
    • document: the output of the whole document

Example

knitr::knit_hooks$set(small.mar = function(before) {
if (before) par(mar = c(1, 1, 1, 1))
})
33 / 37

Output Hooks

  • Output hooks are (render) functions that define how source code and its output is presented.
  • There are 8 output hooks to deal with differnt types of output:
    • source: the source code
    • output: what would have been printed in an R terminal except warnings, messages and errors.
    • warnings: warnings from warning()
    • message: messages from message()
    • error: errors from stop()
    • plot: graphics output
    • inline: output of inline R code
    • chunk: all the output of a chunk
    • document: the output of the whole document

Example

knitr::knit_hooks$set(small.mar = function(before) {
if (before) par(mar = c(1, 1, 1, 1))
})
  • There is for each of the above a default which you can adjust to your needs.
33 / 37

Output Hooks: Example

  • You can e.g. use a hook to consistently style all your tables using kableExtra.

Example

default_source_hook <- knit_hooks$get("source")
knit_hooks$set(
source = function(x, options) {
if(is.null(options$table))
default_source_hook(x, options)
else {
eval(parse(text = x)) %>%
kable("html") %>%
kable_styling("hover", full_width = F)
}
}
)
34 / 37

The here package

  • here::here() is returning the path to the directory where your project file lives in.
35 / 37

The here package

  • here::here() is returning the path to the directory where your project file lives in.

Why is this useful?

  • If an Rmarkdown file is compiled it sets the working directory to the folder where your .rmd file is stored.
  • Usually you do some interactive work before compiling. If you work in an project then the working directory for the interactive part is set to the path of your project file.
  • If your project becomes more complex and you are using subdirectories the working directory set for compilation and interactive work are not necessary the same. This is quite annoying.
35 / 37

The here package

  • here::here() is returning the path to the directory where your project file lives in.

Why is this useful?

  • If an Rmarkdown file is compiled it sets the working directory to the folder where your .rmd file is stored.
  • Usually you do some interactive work before compiling. If you work in an project then the working directory for the interactive part is set to the path of your project file.
  • If your project becomes more complex and you are using subdirectories the working directory set for compilation and interactive work are not necessary the same. This is quite annoying.

Solution

  • use here::here() when setting a path.

Example

load(here::here("Data", "my_dataset.rda"))
35 / 37

Exercises

  1. Create an R Markdown document that is compiled to an HTML document. The document should consist of two sections:
    • Crime Incidents Report Data
    • Explorative Data Analysis.
  2. Use the first section to read in the "Crime Incident Reports" available under Boston crime. Add some information about the source of the data and list all available columns with a short description
    Hint: Take a look at the table RMS_Crime_Incident_Field_Explanation.

  3. Optimize your code chunks so that the document doesn't load the data every time you compile.

  4. Use the second section for an EDA. You are free to do whatever you like but produce at least one table and one graphic.

  5. Hide all your code chunks by setting a global option.

  6. Create a PDF document containing what you did. For this LATEX needs to be installed.

36 / 37

Exercises

  1. Remember that nested ordered lists are not supported by Rmarkdown. Nonetheless, produce one in your HTML and your PDF document.
  2. Also, build some slides using the code you have written. You are free to choose one presentation format among all available formats.
  3. Find out how to always use the current date in the YAML header.
37 / 37

R Markdown

R Markdown provides a framework for combining code, results, and commentary.

You can use R Markdown

  • to generate reports, articles, books ...
  • as an environment in which to do data science, as a lab notebook where you can capture not only what you did, but also what you were thinking.
2 / 37
Paused

Help

Keyboard shortcuts

, , Pg Up, k Go to previous slide
, , Pg Dn, Space, j Go to next slide
Home Go to first slide
End Go to last slide
Number + Return Go to specific slide
b / m / f Toggle blackout / mirrored / fullscreen mode
c Clone slideshow
p Toggle presenter mode
t Restart the presentation timer
?, h Toggle this help
Esc Back to slideshow