R Markdown provides a framework for combining code, results, and commentary.
You can use R Markdown
R Markdown provides a framework for combining code, results, and commentary.
You can use R Markdown
Some interesting links:
R Markdown provides a framework for combining code, results, and commentary.
You can use R Markdown
Some interesting links:
Example:
---title: "Diamond sizes"date: 2016-08-25output: 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** than2.5 *carats*. The distribution of the remainder is shownbelow:```{r, echo = FALSE}smaller %>% ggplot(aes(carat)) + geom_freqpoly(binwidth = 0.01)```If $\frac{\alpha}{\beta} = \gamma$ then $\alpha = \gamma\beta$.
---title: "Diamond sizes"date: 2016-08-25output: 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** than2.5 *carats*. The distribution of the remainder is shownbelow:```{r, echo = FALSE}smaller %>% ggplot(aes(carat)) + geom_freqpoly(binwidth = 0.01)```If $\frac{\alpha}{\beta} = \gamma$ then $\alpha = \gamma\beta$.
example.rmd
in your working directory run knitr::render(example.rmd)
to create an output document. Ctrl + Shift + K
An R Markdown document is a basic text file, with the (conventional) extension .Rmd
.
The example already contains the most important components:
```{r, ...}
and ```
`r
and `
When we click knit in RStudio then
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 .md
file gets processed by pandoc
which creates the final file in the desired output format (e.g. html
, pdf
, word
, ...)The YAML header contains settings passed to pandoc and the rendering functions. Here you can:
.css
) or additional packages for LATEXThe YAML header contains settings passed to pandoc and the rendering functions. Here you can:
.css
) or additional packages for LATEX---title: Habitsauthor: John Doedate: March 22, 2005output: html_document---
YAML Ain't Markup Language, a recursive acronym, to distinguish its purpose as data-oriented, rather than document markup.
---title: Habitsauthor: John Doedate: March 22, 2005output: html_document: toc: true toc_float: collapsed: false smooth_scroll: false css: my_style.cssparams: pi: 3.141593---
html_notebook
- Interactive R Notebooks html_document
- HTML document pdf_document
- PDF documentword_document
- Microsoft Word document Learn more about further output formats at https://rmarkdown.rstudio.com.
# Header 1 ## Header 2 ### Header 3
# Header 1 ## Header 2 ### Header 3
*italics* **bold** This ~~is deleted text.~~ Some code: `lm(y ~ x)`.
italics
bold
Thisis deleted text.
Some code:lm(y ~ x)
.
* Item - Item belonging to item - Another item belonging to item * Item * Item
* Item - Item belonging to item - Another item belonging to item * Item * Item
1. First item - First subitem - Second subitem 2. Second item 3. Third item
* Item - Item belonging to item - Another item belonging to item * Item * 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.
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).
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).
First paragraph Second paragraph
First paragraph
Second paragraph
A new paragraph is started by a blank line.
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:
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:
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)=1√2πexp(−12x2).
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:
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)=1√2πexp(−12x2).
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)=1√2πexp(−12x2)
align
can be used \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}
align
can be used \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}
(a+b)3=(a+b)(a+b)2=(a+b)(a2+2ab+b2)=a3+3a2b+3ab2+b3(1)(2)(3)
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 filecache
(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 documentSome 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 filecache
(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 documentFor a complete list, we refer to the knitr
documentation: Chunk options.
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 filecache
(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 documentFor a complete list, we refer to the knitr
documentation: Chunk options.
Ctrl + Alt + I
to insert a new R code chunk.```{r lin_reg, echo=TRUE, cache = TRUE}x <- runif(100)y <- 0.4 * x + rnorm(100)lm(y ~ x)```
```{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()
.
```{r setup, include=FALSE}knitr::opts_chunk$set(echo=FALSE, warning=FALSE, message=FALSE)```
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.
```{r, echo=FALSE}x <- 4y <- 38answer <- x + y```The answer is `r answer`
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.
```{r, echo=FALSE}x <- 4y <- 38answer <- x + y```The answer is `r answer`
The answer is 42.
Tables can be created as follows:
| Right | Left | Default | Center ||------:|:-----|---------|:------:|| 12 | 12 | 12 | 12 | | 123 | 123 | 123 | 123 | | 1 | 1 | 1 | 1 |
Tables can be created as follows:
| 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 |
Tables can be created as follows:
| 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.
kable
knitr::kable()
is probably the easiest way to transform a matrix or a data frame into a table.```{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")```
kable
knitr::kable()
is probably the easiest way to transform a matrix or a data frame into a table.```{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 |
kableExtra
knitr::kable()
) depends on the underlying css
(in case of an HTML document) or the generated LATEX code. kableExtra
allows to format your knitr::kable()
table without the use of css
or LATEXkableExtra
knitr::kable()
) depends on the underlying css
(in case of an HTML document) or the generated LATEX code. kableExtra
allows to format your knitr::kable()
table without the use of css
or LATEX```{r}library(magrittr)library(kableExtra)knitr::kable(result, align = c("r", "l", "l", "c"), format = "html") %>% kableExtra::kable_styling(bootstrap_options = "bordered")```
kableExtra
knitr::kable()
) depends on the underlying css
(in case of an HTML document) or the generated LATEX code. kableExtra
allows to format your knitr::kable()
table without the use of css
or LATEX```{r}library(magrittr)library(kableExtra)knitr::kable(result, align = c("r", "l", "l", "c"), format = "html") %>% kableExtra::kable_styling(bootstrap_options = "bordered")```
xtable
xtable
provides more functionality than kable but is a bit more difficult to use.results='asis'
in the chunk options, otherwise it gets formatted and will not work as intended.xtable
xtable
provides more functionality than kable but is a bit more difficult to use.results='asis'
in the chunk options, otherwise it gets formatted and will not work as intended.```{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)```
xtable
xtable
provides more functionality than kable but is a bit more difficult to use.results='asis'
in the chunk options, otherwise it gets formatted and will not work as intended.```{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 |
stargazer
stargazer
takes model objects as input and automatically creates an output table ```{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")```
stargazer
stargazer
takes model objects as input and automatically creates an output table ```{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) | |
Constant | 39.686*** |
(1.715) | |
```{r, fig.height = 5}hist(rnorm(1000))```
```{r, fig.height = 5}hist(rnorm(1000))```
[This is a link to the R Markdown book](https://bookdown.org/yihui/rmarkdown/)
[This is a link to the R Markdown book](https://bookdown.org/yihui/rmarkdown/)

[This is a link to the R Markdown book](https://bookdown.org/yihui/rmarkdown/)

```{r, out.width = "500px", fig.align='center'}knitr::include_graphics("path/to/figure.png")```
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
plotly
for interactive plots or
leaflet
for interactive maps. plotly
for interactive plots or
leaflet
for interactive maps. ```{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')))```
```{r, out.width='100%'}library(leaflet)leaflet() %>% addTiles() %>% setView(7.005070, 51.463675,zoom = 17) %>% addMarkers( 7.005070, 51.463675 )```
```{r, out.width='100%'}library(leaflet)leaflet() %>% addTiles() %>% setView(7.005070, 51.463675,zoom = 17) %>% addMarkers( 7.005070, 51.463675 )```
DT
package also allows us to include interactive tables. ```{r}DT::datatable( head(iris, 10), fillContainer = TRUE, options = list(pageLength = 5))```
DT
package also allows us to include interactive tables. ```{r}DT::datatable( head(iris, 10), fillContainer = TRUE, options = list(pageLength = 5))```
knitr
user. knitr
user. # Template for a chunk hookknitr::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 } })
knitr
user. # Template for a chunk hookknitr::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 == TRUE
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).small.mar = TRUE
put the following code chunk
at the top of your document. ```{r, eval = FALSE, echo=TRUE}knitr::knit_hooks$set(small.mar = function(before) { if (before) par(mar = c(1, 1, 1, 1)) })```
small.mar = TRUE
put the following code chunk
at the top of your document. ```{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. ```{r, small.mar = TRUE}hist(rnorm)```
source
: the source codeoutput
: 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 outputinline
: output of inline R codechunk
: all the output of a chunkdocument
: the output of the whole document source
: the source codeoutput
: 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 outputinline
: output of inline R codechunk
: all the output of a chunkdocument
: the output of the whole document knitr::knit_hooks$set(small.mar = function(before) { if (before) par(mar = c(1, 1, 1, 1)) })
source
: the source codeoutput
: 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 outputinline
: output of inline R codechunk
: all the output of a chunkdocument
: the output of the whole document knitr::knit_hooks$set(small.mar = function(before) { if (before) par(mar = c(1, 1, 1, 1)) })
kableExtra
. 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) } })
here
packagehere::here()
is returning the path to the directory where your project file lives in. here
packagehere::here()
is returning the path to the directory where your project file lives in. Why is this useful?
.rmd
file is stored.here
packagehere::here()
is returning the path to the directory where your project file lives in. Why is this useful?
.rmd
file is stored.here::here()
when setting a path.load(here::here("Data", "my_dataset.rda"))
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
.
Optimize your code chunks so that the document doesn't load the data every time you compile.
Use the second section for an EDA. You are free to do whatever you like but produce at least one table and one graphic.
Hide all your code chunks by setting a global option.
Create a PDF document containing what you did. For this LATEX needs to be installed.
R Markdown provides a framework for combining code, results, and commentary.
You can use R Markdown
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 |