class: title-slide, center, bottom # 04 - R Markdown ## Data Science with R · Summer 2021 ### Uli Niemann · Knowledge Management & Discovery Lab #### [https://brain.cs.uni-magdeburg.de/kmd/DataSciR/](https://brain.cs.uni-magdeburg.de/kmd/DataSciR/) .courtesy[📷 Photo courtesy of Ulrich Arendt] --- class: middle, center <iframe src="https://player.vimeo.com/video/178485416?color=428bca&title=0&byline=0&portrait=0" width="800" height="450" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe> <p><a href="https://vimeo.com/178485416">What is R Markdown?</a> from <a href="https://vimeo.com/rstudioinc">RStudio, Inc.</a> on <a href="https://vimeo.com">Vimeo</a>.</p> ??? - basic idea: rmd = text file that includes narrative text, code and results - the same rmd doc can be "rendered" into multiple output types such as html, pdf, or word - "rendered": R code is run and the rmd is converted to an md doc, and this md doc is in turn converted to the desired output format --- class: middle, center <iframe src="https://rmarkdown.rstudio.com/gallery.html" width="100%" height="550px"></iframe> ??? - types of output formats --- ## Why reproducible documents? <center> <iframe src="https://www.youtube.com/embed/s3JldKoA0zw?rel=0" width="800px" height="450px"></iframe> </center> <https://youtu.be/s3JldKoA0zw> ??? application scenario: write research paper based on data analysis results - repetitive and tedious manual workflow - raw data is stored in Excel - then manually run data analysis scripts in R - make charts - copy-paste results and visualizations into your docx, pptx or latex file - maybe you do the analysis already during the data collection phase and you get 2 more observations which forces you to redo all of these steps - R Markdown is a suitable tool to automatize such a workflow. --- ## R Markdown - [Introduction](#intro) - [Output formats](#output) - [Components of an `.Rmd` file](#structure): Markdown, Code, YAML - [`knitr` and `pandoc`](#how-it-works) - Basic [chunk options](#chunk-options) - Embedding [graphics & tables](#tables) - [Caching](#caching) - [References and bibliography](#references) - [Parametrized documents](#params) - [R Markdown extensions](#extensions) --- name: intro ## Introduction .pull-left60[ **R Markdown** is a file format to combine **code**, the associated **results** and **narrative text** in a simple text file, to create **reproducible reports** which can be **flexibly distributed in multiple ways**. An R Markdown document is saved as `.Rmd` file. It contains both the (`R`) code and a prose description of a data analysis task. The R Markdown document can be rendered as HTML, PDF, Word and various other output formats. **Pros** of R Markdown documents: - **reproducibility** (reduce **copy&paste**) - **simple Markdown syntax** for text - a **single source document** that can be rendered for different target audiences and purposes - **simple, future-proof file format** that can be managed by a version control system like Git or SVN ] .pull-right40[ <img src="figures//04-rmarkdown-logo.png" width="40%" style="display: block; margin: auto;" /> <img src="figures//04-three_outputs.png" width="100%" style="display: block; margin: auto;" /> ] ??? - file extension - Jupyter notebooks in Python (combine text, code and results) - flexibility in terms of type of output document - flexibility in terms of target audience -> parametrized reports - you: lab notebook containing code, conclusions and reasoning behind your analysis - decision makers: hide code, focus on charts and conclusions - colleagues: focus both on conclusions and code to ensure reproducibility and to facilitate collaborating - rmd is plain text file so it can be managed by a version control system - simple syntax --- name: output ## The process of "knitting" an R Markdown file <img src="figures//04-rmarkdown_sketch.png" width="100%" style="display: block; margin: auto;" /> .footnote[ .font90[ A .Rmd file contains narrative text in Markdown syntax and (`R`) code. The `knitr` package provides functions to execute the code, collect the results (statistics, tables, plots, etc.) and combine them with the Markdown text into a Markdown file (.md). Pandoc, a universal document converter, then converts this Markdown file into the requested output format, e.g., .html, .pdf or .docx. ] ] ??? - process: Rmd -> md -> rendered document - rmd: md + r-code - knitr: run code and combine these code results (charts, models, console output) with md markup of rmd file - pandoc (general file converter) converts this augmented md file to the desired output HTML, pdf, word etc. - simplified process - based on the output, more packages are needed - e.g. blogdown: Hugo required (open-source static site generator) --- name: structure ## Components of an R Markdown file .panelset[ .panel[.panel-name[Structure] .pull-left60[ <img src="figures//04-rmd_first_example_1.png" width="100%" style="display: block; margin: auto;" /> ] .pull-right40[ - **YAML header** (metadata) - enclosed by lines with three dashes - collection of key-value pairs separated by colons - narrative text as **Markdown markup** - **`R` code** - as **code chunks** surrounded by <code>`</code><code>`</code><code>`{r}</code> and <code>`</code><code>`</code><code>`</code> - as **inline code** surrounded by <code>`r </code> and <code>`</code> ] ] .panel[.panel-name[Output] <iframe src="04-rmd-intro.html" width="100%" height="500px"></iframe> ] .panel[.panel-name[]] ] ??? - YAML header: meta data - code chunks: can be R but there are other languages supported, such as python, javascript, sql, ruby - Markdown text - inline code: allows for dynamic content (e.g.how many records) using simple commands - no need for manual copy and paste of the code output into the narrative text. --- exclude: true class: exercise-blue, middle ## Your turn 1 Make yourself familiar with R Markdown documents. - In RStudio, create a new RMarkdown document with HTML as output format. - Click on the **Knit** button to render a HTML file. Locate the folder of the HTML file in the "Files" tab. Try to knit the rmd file with the Keyboard shortcut **Ctrl**+**⇧Shift**+**K**. - Click on the small downwards arrow right to the **Knit** button and try to render the document as Word and PDF output, respectively. - Click on the _gear_ button right to the **Knit** button to explore the R Markdown format options. What happens when you click on the green arrow at the right of the third code chunk? (You can accomplish the same by moving the cursor into the code chunk and then pressing **Ctrl**+**⇧Shift**+**Enter↵**.) (⟶ [**Notebook mode**](https://bookdown.org/yihui/rmarkdown/notebook.html)) --- ## Markdown **Markdown** is a **simplified, plain text formatting system** used to structure text using **markup tags**. In contrast to other markup languages like **HTML** and **XML**, Markdown markup is easier to read and write due to its simpler tags, e.g. `#` instead of `<h1></h1>` for headers of level 1. .pull-left[ <img src="figures//04-html_example.png" width="85%" /> ] .pull-right[ **Markdown Quick Reference** in RStudio: **Help** `\(\rightarrow\)` **Markdown Quick Reference** <img src="figures//04-rstudio-markdown-quick-ref-1.png" width="100%" /> ] ??? - no closing tag - accomplish the same output with much less typing --- class: middle Learn Markdown basics interactively on <https://www.markdowntutorial.com> in ~10 minutes. <iframe src="https://www.markdowntutorial.com" width="100%" height="500px"></iframe> --- class: middle .pull-left[ ### Syntax \*italic\* and \*\*bold\*\* <span>`</span>inline code` subscript~2~/superscript^2^ \~\~strikethrough\~\~ escaped: \\* \\_ \\\ en-dash: -- em-dash: --- \# Header level 1 \#\# Header level 2 Manual line break: (2+ space characters at the line end): Backe, backe, Kuchen, der Bäcker hat gerufen! Backe, backe, Kuchen,**SPACE** **SPACE** der Bäcker hat gerufen! ] .pull-right[ ### Result *italic* and **bold** `inline code` subscript<sub>2</sub>/superscript<sup>2</sup> ~~strikethrough~~ escaped: \* \_ \\ en-dash: – em-dash: — # Header level 1 ## Header level 2 Backe, backe, Kuchen, der Bäcker hat gerufen! Backe, backe, Kuchen, der Bäcker hat gerufen! ] --- class: middle .pull-left[ ### Syntax \- unordered list \- subitem 1 (4 **SPACE**) \- subitem 2 \- subsubitem (8 **SPACE**) <span>1.</span> ordered list <span>1.</span> item 2 1. subitem 2.1 1. subitem 2.2 inline equation: $A = \pi\cdot r^{2}$ math block: <span>$</span>$A = \pi\cdot r^{2}$$ \[linked text\](https://www.ovgu.de/) Footnote[^1] [^1]: This text belongs to the footnote. <span><!-</span>- This is a comment that will not be displayed.-<span>-></span> ] .pull-right[ ### Result - unordered list - subitem 1 - subitem 2 - subsubitem 1. ordered list 1. item 2 1. subitem 2.1 1. subitem 2.2 inline equation: `\(A = \pi\cdot r^{2}\)` math block: `$$A = \pi\cdot r^{2}$$` [linked text](https://www.ovgu.de/) Footnote<sup>1</sup> .footnote[[1] This text belongs to the footnote.] ] --- exclude: true class: exercise-blue, middle ## Your turn 2 In the Rmd document you have created in the previous exercise, locate the words/phrases that are written - in bold face, - in italics, - as headers of level 2, - as inline code. Consult the _Markdown Quick Reference_ to find out a way how to include an image using Markdown only. Then, include a photo of the Magdeburg Cathedral using the following URL: <https://t1p.de/lu81>. (shortened version of <https://upload.wikimedia.org/wikipedia/commons/thumb/8/86/Magdeburg%2C_domtsjerke.jpg/512px-Magdeburg%2C_domtsjerke.jpg>) --- name: how-it-works ## `knitr` The `knitr` package is responsible for evaluating the `R` code within an `.Rmd` file and combining the results, figures, code and the Markdown text into a `.md` file. .pull-left70[ `R` code can be embedded within an `.Rmd` file in two ways: A) as **inline code** within markdown text delimited by single backticks tags to run a single command: <code>`r` </code> B) as separate **code chunk** delimited by triple backticks tags to run multiple commands: ````markdown ```{r} some code ``` ```` Code chunks can be inserted with the <img src="figures//04-insert.png" width="88" /> button in the toolbar or using the keyboard shortcut **Ctrl + Alt + I**. ] .pull-right30[ <img src="figures//04-knitr.png" width="100%" /> ] ??? - knitr doesnt need to be attached at the start of an R Markdown document - knitr removes backticks, runs the code and returns the code, and the output - backtick-backtick-backtick is minimum to define a starting R chunk --- class: center, middle <img src="figures//04-chunk.png" width="100%" /> ??? structure of a code chunk - code enclosed by 3 backticks before and after - after first 3 backticks: code engine, chunk label, comma-separated chunk options in curly brackets - engine: option to switch between languages: not limited to R, can handle also python, bash, css, sql --- name: chunk-options ## Chunk options `knitr` allows to customize each code chunk in the report by providing **optional arguments**: The most important options include: - whether to show or hide the source code in the rendered document - whether to evaluate the code - whether warnings and messages should be shown or suppressed in the rendered document - figure dimension Chunk options are specified comma-separated inside the curly brackets after `r`. --- ## Chunk options By default, R Markdown includes **messages**, **warnings** and **error messages**. ````markdown ```{r} c(1,2,3) + c(4,5) ``` ```` ``` ## Warning in c(1, 2, 3) + c(4, 5): longer object length is not a multiple of shorter object ## length ``` ``` ## [1] 5 7 7 ``` -- We can override this default behavior by setting `warning = FALSE` inside the code chunk header. ````markdown ```{r, warning = FALSE} c(1,2,3) + c(4,5) ``` ```` <!-- <span style="color: yellow;">warning = FALSE</span> --> ``` ## [1] 5 7 7 ``` ??? - optional arguments - by default, warning = TRUE - message = FALSE: don't show messages (e.g. when attaching libraries) - error = TRUE: continue rendering even if code returns an error (debugging, teachings) - default: error = FALSE, causes knitting to fail if there is a single error in the document --- ## Popular chunk options Option | Description | Default :----- | :---------- | :--------------------------- `echo` | Should the code be displayed? | `TRUE` `eval` | Should the code be run? | `TRUE` `include` | Should the code and the code results (figures, console output) be displayed? | `TRUE` `fig.width` | Figure width in inch | `7L` `fig.height` | Figure height in inch | `7L` `fig.align` | Figure alignment | `"default"` `warning` | Should warnings be displayed? | `TRUE` `message` | Should messages be displayed? | `TRUE` .content-box-blue[ - Run `knitr::opts_chunk$get()` to see the current default values for all chunk options. - Use `knitr::opts_chunk$set()` to modify these defaults, e.g. `knitr::opts_chunk$set(warning = FALSE)`. Example: `knitr::opts_chunk$set(fig.width = 8)` changes the default width of a figure to 8 inch. ] ??? - echo = FALSE prevents that the code is shown in the rendered doc; still gets executed; useful for sending the document to your boss/supervisor who is only interested in the results and not the code - eval= FALSE prevents code from being evaluated. useful for displaying example code, or for disabling a large block of code without commentating each line - include = FALSE runs the code, but doesn't show the code or the results in the final document (supresses output) - When you are trying to set echo = FALSE, results = 'hide', warning = FALSE, and message = FALSE, chances are you simply mean a single option include = FALSE instead of suppressing different types of text output individually. https://bookdown.org/yihui/rmarkdown/r-code.html - results = 'hide': hides printed output --- class: middle A list of all chunk options is available at <https://yihui.org/knitr/options/#chunk-options>. <iframe src="https://yihui.org/knitr/options/#chunk-options" width="100%" height="530px"></iframe> --- exclude: true class: exercise-blue, middle ## Quiz Consider the code chunk below. Answer the following questions: - Will the code be displayed in the final document? - Will the code be run? - Will the plot be shown in the final document? .font120[ ````markdown ```{r boxplot-iris-species, echo=FALSE} library(ggplot2) ggplot(iris, aes(x = Species, y = Sepal.Length)) + geom_boxplot() ``` ```` ] --- exclude: true class: exercise-blue, middle <img src="figures/_gen/04/ex-1-1.png" width="576" /> - Will the code be displayed in the final document? ✘ - Will the code be run? ✔ - Will the plot be shown in the final document? ✔ --- ## Setup chunk ````markdown ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = FALSE) library(tidyverse) ``` ```` .content-box-green[ The setup chunk at the beginning of the document is useful to: - set global options for the whole document - load required packages - load all required datasets Before running a code chunk in Nodebook mode, R Markdown will always execute the setup code chunk first. ] ??? - This chunk is executed, but neither code nor output are shown --- exclude: true class: exercise-blue, middle ## Your turn 3 Add the following code chunk to your R Markdown document. Name it "faithful". ```r library(tidyverse) ggplot() + geom_contour_filled(data = faithfuld, aes(eruptions, waiting, z = density), bins = 10) + geom_point(data = faithful, aes(eruptions, waiting), color = "white", alpha = 0.75) + guides(fill = FALSE) + theme_minimal() ``` - Render the Rmd file and inspect the output HTML document. - Find a way to get rid of the console _message_ when the `tidyverse` package is loaded. - Run the "faithful" code chunk separately in Notebook mode. - Change the figure width to 30 cm. Rerender the document and inspect the result. - Replace `library(tidyverse)` with `library(ggplot2)`. - Restart the session. Cut `library(ggplot2)` from the code chunk and place it into the setup chunk. Try to run the "faithful" code chunk. Does it still work? - Restart the session. Cut `library(ggplot2)` from the setup chunk and place it into a new unnamed chunk (shortcut **Ctrl+Alt+I**) beneath the "faithful" chunk. Try to run the "faithful" code chunk. Does it (still) work? - Restart the session. Place the unnamed code chunk right above the "faithful" chunk. Try to run the "faithful" code chunk. Does it (still) work? ??? - the order of execution matters - setup chunk is treated in a special way --- ## External graphics .pull-left70[ ````markdown ```{r r-markdown-logo, fig.cap="R Markdown Logo"} knitr::include_graphics("figures/rmarkdown-logo.png") ``` ```` ] .pull-right30[ <img src="figures//04-rmarkdown-logo.png" width="100%" /> <center> .caption[ R Markdown Logo ] </center> ] --- name: tables ## Tables: kable ````markdown ```{r kable-iris} knitr::kable(head(iris), caption = "A knitr kable table") ``` ```` <table> <caption>A knitr kable table</caption> <thead> <tr> <th style="text-align:right;"> Sepal.Length </th> <th style="text-align:right;"> Sepal.Width </th> <th style="text-align:right;"> Petal.Length </th> <th style="text-align:right;"> Petal.Width </th> <th style="text-align:left;"> Species </th> </tr> </thead> <tbody> <tr> <td style="text-align:right;"> 5.1 </td> <td style="text-align:right;"> 3.5 </td> <td style="text-align:right;"> 1.4 </td> <td style="text-align:right;"> 0.2 </td> <td style="text-align:left;"> setosa </td> </tr> <tr> <td style="text-align:right;"> 4.9 </td> <td style="text-align:right;"> 3.0 </td> <td style="text-align:right;"> 1.4 </td> <td style="text-align:right;"> 0.2 </td> <td style="text-align:left;"> setosa </td> </tr> <tr> <td style="text-align:right;"> 4.7 </td> <td style="text-align:right;"> 3.2 </td> <td style="text-align:right;"> 1.3 </td> <td style="text-align:right;"> 0.2 </td> <td style="text-align:left;"> setosa </td> </tr> <tr> <td style="text-align:right;"> 4.6 </td> <td style="text-align:right;"> 3.1 </td> <td style="text-align:right;"> 1.5 </td> <td style="text-align:right;"> 0.2 </td> <td style="text-align:left;"> setosa </td> </tr> <tr> <td style="text-align:right;"> 5.0 </td> <td style="text-align:right;"> 3.6 </td> <td style="text-align:right;"> 1.4 </td> <td style="text-align:right;"> 0.2 </td> <td style="text-align:left;"> setosa </td> </tr> <tr> <td style="text-align:right;"> 5.4 </td> <td style="text-align:right;"> 3.9 </td> <td style="text-align:right;"> 1.7 </td> <td style="text-align:right;"> 0.4 </td> <td style="text-align:left;"> setosa </td> </tr> </tbody> </table> ??? - kable: robust table generator for html, pdf word docs --- R Markdown Cookbook: <https://bookdown.org/yihui/rmarkdown-cookbook/kable.html> <iframe src="https://bookdown.org/yihui/rmarkdown-cookbook/kable.html" width="100%" height="530px"></iframe> --- `kableExtra` package: .font90[<https://cran.r-project.org/web/packages/kableExtra/vignettes/awesome_table_in_html.html>] <iframe src="https://cran.r-project.org/web/packages/kableExtra/vignettes/awesome_table_in_html.html" width="100%" height="530px"></iframe> ??? - custom style: cell backgrounds, conditional formatting - multi-row and multi-column cells - tooltips - etc. --- ## Tables: DT datatable `DT` is an R interface to the DataTables JavaScript library. ````markdown ```{r} DT::datatable(iris) ``` ```` .font70[ <iframe src="figures//04-dt-iris.html" width="70%" height="400px"></iframe> ] ??? - paginated table - sort rows by column - search for strings - modify the number of rows shown simultaneously on one page , fillContainer = FALSE --- DT package: <https://rstudio.github.io/DT/> <iframe src="https://rstudio.github.io/DT/" width="100%" height="530px"></iframe> --- ## Tables: gt [`gt`](https://gt.rstudio.com/): "Easily generate information-rich, publication-quality tables from R" ````markdown ```{r} gt::gt(head(iris)) ``` ````
Sepal.Length
Sepal.Width
Petal.Length
Petal.Width
Species
5.1
3.5
1.4
0.2
setosa
4.9
3.0
1.4
0.2
setosa
4.7
3.2
1.3
0.2
setosa
4.6
3.1
1.5
0.2
setosa
5.0
3.6
1.4
0.2
setosa
5.4
3.9
1.7
0.4
setosa
??? - alternative --- `gt`: "Easily generate information-rich, publication-quality tables from R" <https://gt.rstudio.com/> <iframe src="https://gt.rstudio.com/" width="100%" height="530px"></iframe> ??? --- name: caching ## Caching By default, all code chunks are **recomputed every time** you knit the file. For code chunks that contain **time-demanding operations**, you can use the `cache = TRUE` option. During the **first knit run**, the code is executed and the results are stored in a **local cache**. When the document is knitted again, the results are loaded from cache if the code chunk has not been edited since the first run. If the **code or data changes**, the code will be rerun and the **old cache will be overwritten**. ````markdown ```{r, cache=TRUE} ...time-consuming computations... ``` ```` --- exclude: true class: exercise-blue, middle ## Your turn 4 Add the following code chunk to your R Markdown document. Name it "heavy-computing". ```r tic <- Sys.time() mean(1:1000000000) toc <- Sys.time() time_spent <- difftime(toc, tic, units = "secs") ``` Below the chunk, add an inline code chunk that prints `time_spent`. 1. Knit the document. What is the value of `time_spent`? 1. Knit the document again. What is the value of `time_spent`? 1. Add result caching as code chunk option to "heavy-computing". Knit the document again. What is the value of `time_spent`? 1. Knit the document again. What is the value of `time_spent`? --- ## Labeling and reusing code chunks Code chunks can be given a **label**. The label is specified directly after <code>```{r</code>. Code chunk labels can be useful to **avoid code duplication**. By using the argument `ref.label` in a later code chunk, the code from the referenced code chunk is copied over to and run in the current code chunk. Example: ````markdown ```{r iris_plot, echo=FALSE, eval=FALSE} library(ggplot2) ggplot(iris, aes(Species, Sepal.Length)) + geom_boxplot() ``` ```` -- .pull-left[ ````markdown ```{r, ref.label='iris_plot', echo = FALSE} ``` ```` ] .pull-right[ <img src="figures/_gen/04/unnamed-chunk-1-2.png" width="425.196850393701" /> ] --- ## Inline `R` code You can embed `R` code into the text of your document with the <code>`r `</code> syntax. R Markdown will run the code and replace it with its result, which should be a piece of text, such as a character string or a number. For example, the line below uses embedded R code to create a complete sentence: <pre> A random sample of 5 numbers from the set of numbers between <br />1 and 10 is `r sample(1:10, 5)`. </pre> -- When you render the document the result will appear as: <pre> A random sample of 5 numbers from the set of numbers between <br />1 and 10 is 7, 8, 4, 2, 1. </pre> Inline code provides a useful way to make your reports completely automatable. --- ## Pandoc .pull-left0[ R Markdown uses the document conversion application [Pandoc](https://pandoc.org/) to convert a `.md` file to a variety of output formats. - using RStudio via the <img src="figures//04-knit.png" width="79" /> button - in the console via `rmarkdown::render()` ] .pull-right30[ <img src="figures//04-pandoc.png" width="100%" /> ] --- ## YAML .pull-left80[ Properties of the whole document can be set via the **YAML** (_Yet Another Markup Language_) header. The YAML header consists of a collection of **key-value pairs** separated by colons. The YAML header itself is demarked by lines with three dashes. ] .pull-right20[ <img src="figures//04-yaml.jpg" width="100%" /> ] Mandatory YAML specification: `output: html_document` Other output formats: - pdf_document - word_document - beamer_presentation - slidy_presentation - ioslides_presentation - md_document - and [many more...](https://rmarkdown.rstudio.com/gallery.html) --- ## Customize output layout Each R Markdown output template is a collection of knitr and pandoc options. You can customize your output by overwriting the default options that come with the template. For example, the YAML header below causes `knitr` to include a table of contents in the pdf output document: --- title: "My R Markdown Document" output: pdf_document: toc: true --- ??? Move the html_document header element to its own line, and indent it to be a subelement of output. Add a colon, : after html_document. Add toc (for a table of contents) and number_sections subelements to html_document, setting both to true (lower case). Re-render the document. --- <img src="figures//04-yaml-options.png" width="60%" style="display: block; margin: auto;" /> .footnote[.font70[From the RStudio R Markdown Cheat Sheet]] --- exclude: true class: exercise-blue, middle ## Your turn 5 1. In the YAML header, add the fields "author" and "date". Set the values so that in the rendered output document, your name and the current date (`Sys.date()`) will be shown. 2. Further, change the document visual theme of the HTML document. To do so, inspect the documentation of `?html_document` to find out which themes can be chosen. Go to <https://bootswatch.com/> to see a preview of the available themes and pick the theme you like most. --- name: references ## Bibliography --- output: html_document bibliography: refs.bib csl: ieee.csl --- Insert a reference [@bib-key1; @bib-key2] in your Markdown text. → The bibliography will be inserted at the end of the document. .footnote[ More information about bibliographies in R Markdown documents on the [R Markdown Website](https://rmarkdown.rstudio.com/authoring_bibliographies_and_citations.html) from RStudio. ] ??? - Pandoc can automatically generate citations and a bibliography in a number of styles. In order to use this feature, you will need to specify a **bib file** using the "bibliography" metadata field in a YAML metadata section. - citations inside square brackets, separated by semicolons - citation style: By default, pandoc will use a Chicago author-date format for citations and references. To use another style, you will need to specify a CSL 1.0 style file in the csl metadata field. --- name: params ## Parametrized reports Create document templates to produce different reports with a single `.Rmd` using **parameters**. Application scenarios: - serial letters - separate reports for different subsets of a dataset - documents with different `knitr` behavior (e.g. one document showing the code and one document not showing the code) <iframe src="04-rmarkdown-materials/04-rmarkdown-parameter.Rmd" width="60%" height="300px"></iframe> --- ## Parametrized reports Parametrized reports can be created using the **Knit** button, or by calling `rmarkdown::render()`. The later option is particularly useful if you have to create many parametrized reports. Example: create a custom report for each species of Iris data. ```r library(dplyr) reports <- tibble( my_species = unique(iris$Species), output_file = paste0("slides/04-rmarkdown-materials/iris-", my_species, ".html"), params = purrr::map(my_species, ~ list(my_species = .)) ) reports ``` ``` ## # A tibble: 3 x 3 ## my_species output_file params ## <fct> <chr> <list> ## 1 setosa slides/04-rmarkdown-materials/iris-setosa.html <named list [1]> ## 2 versicolor slides/04-rmarkdown-materials/iris-versicolor.html <named list [1]> ## 3 virginica slides/04-rmarkdown-materials/iris-virginica.html <named list [1]> ``` --- ## Parametrized reports .content-box-green[ .font90[ `purrr::pwalk` applies a function to a list of arguments. It is similar to `purrr::pmap`, but instead of returning an output value, it is called for its **side-effects**. Here, it is used to iterate over each row of the `reports` tibble, calling `rmarkdown::render()` to generate a `.html` document for each Iris species. ] ] ```r reports %>% select(output_file, params) %>% mutate(output_file = here::here(output_file)) %>% purrr::pwalk(rmarkdown::render, input = "04-rmarkdown-materials/04-rmarkdown-parameter.Rmd") ``` ``` ## | | | 0% | |.................... | 25% ## ordinary text without R code ## ## | |........................................ | 50% ## label: iris-setup (with options) ## List of 3 ## $ include: logi FALSE ## $ message: logi FALSE ## $ warning: logi FALSE ## ## | |............................................................ | 75% ## ordinary text without R code ## ## | |................................................................................| 100% ## label: hist ``` ``` ## ## "C:/PROGRA~1/Pandoc/pandoc" +RTS -K512m -RTS 04-rmarkdown-parameter.utf8.md --to html4 --from markdown+autolink_bare_uris+tex_math_single_backslash --output pandoc4a744a8c641c.html --lua-filter "C:\Users\ulini\R\win-library\4.0\rmarkdown\rmarkdown\lua\pagebreak.lua" --lua-filter "C:\Users\ulini\R\win-library\4.0\rmarkdown\rmarkdown\lua\latex-div.lua" --self-contained --variable bs3=TRUE --standalone --section-divs --template "C:\Users\ulini\R\win-library\4.0\rmarkdown\rmd\h\default.html" --no-highlight --variable highlightjs=1 --variable theme=bootstrap --include-in-header "C:\Users\ulini\AppData\Local\TEMP_~1\Rtmpg7VdgF\rmarkdown-str4a745f5950d.html" --mathjax --variable "mathjax-url:https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML" ## | | | 0% | |.................... | 25% ## ordinary text without R code ## ## | |........................................ | 50% ## label: iris-setup (with options) ## List of 3 ## $ include: logi FALSE ## $ message: logi FALSE ## $ warning: logi FALSE ## ## | |............................................................ | 75% ## ordinary text without R code ## ## | |................................................................................| 100% ## label: hist ``` ``` ## ## "C:/PROGRA~1/Pandoc/pandoc" +RTS -K512m -RTS 04-rmarkdown-parameter.utf8.md --to html4 --from markdown+autolink_bare_uris+tex_math_single_backslash --output pandoc4a741d083b50.html --lua-filter "C:\Users\ulini\R\win-library\4.0\rmarkdown\rmarkdown\lua\pagebreak.lua" --lua-filter "C:\Users\ulini\R\win-library\4.0\rmarkdown\rmarkdown\lua\latex-div.lua" --self-contained --variable bs3=TRUE --standalone --section-divs --template "C:\Users\ulini\R\win-library\4.0\rmarkdown\rmd\h\default.html" --no-highlight --variable highlightjs=1 --variable theme=bootstrap --include-in-header "C:\Users\ulini\AppData\Local\TEMP_~1\Rtmpg7VdgF\rmarkdown-str4a741be26f81.html" --mathjax --variable "mathjax-url:https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML" ## | | | 0% | |.................... | 25% ## ordinary text without R code ## ## | |........................................ | 50% ## label: iris-setup (with options) ## List of 3 ## $ include: logi FALSE ## $ message: logi FALSE ## $ warning: logi FALSE ## ## | |............................................................ | 75% ## ordinary text without R code ## ## | |................................................................................| 100% ## label: hist ``` ``` ## ## "C:/PROGRA~1/Pandoc/pandoc" +RTS -K512m -RTS 04-rmarkdown-parameter.utf8.md --to html4 --from markdown+autolink_bare_uris+tex_math_single_backslash --output pandoc4a745cf74e4.html --lua-filter "C:\Users\ulini\R\win-library\4.0\rmarkdown\rmarkdown\lua\pagebreak.lua" --lua-filter "C:\Users\ulini\R\win-library\4.0\rmarkdown\rmarkdown\lua\latex-div.lua" --self-contained --variable bs3=TRUE --standalone --section-divs --template "C:\Users\ulini\R\win-library\4.0\rmarkdown\rmd\h\default.html" --no-highlight --variable highlightjs=1 --variable theme=bootstrap --include-in-header "C:\Users\ulini\AppData\Local\TEMP_~1\Rtmpg7VdgF\rmarkdown-str4a74655769f8.html" --mathjax --variable "mathjax-url:https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML" ``` --- ## Parametrized reports <iframe src="04-rmarkdown-materials/iris-setosa.html" width="32%" height="350px"></iframe><iframe src="04-rmarkdown-materials/iris-versicolor.html" width="32%" height="350px"></iframe><iframe src="04-rmarkdown-materials/iris-virginica.html" width="32%" height="350px"></iframe> .footnote[ More information in R Markdown: The Definitive Guide. [Chapter Parameterized reports](https://bookdown.org/yihui/rmarkdown/parameterized-reports.html). ] --- name: extensions class: middle, center <iframe src="https://rmarkdown.rstudio.com/gallery.html" width="100%" height="550px"></iframe> --- ## htmlwidgets: <http://www.htmlwidgets.org/index.html> <iframe src="http://www.htmlwidgets.org/index.html" width="100%" height="550px"></iframe> --- ## flexdashboards: .font80[<https://rmarkdown.rstudio.com/flexdashboard/>] <iframe src="http://jkunst.com/flexdashboard-highcharter-examples/pokemon/" width="100%" height="550px"></iframe> --- ## xaringan presentations: .font80[<https://slides.yihui.org/xaringan/>] <iframe src="https://slides.yihui.org/xaringan/" width="100%" height="550px"></iframe> --- ## blogdown websites: .font80[<https://bookdown.org/yihui/blogdown/>] Example blogdown website: <https://alison.rbind.io/> <iframe src="https://alison.rbind.io/" width="100%" height="500px"></iframe> --- ## bookdown: <https://bookdown.org/> <iframe src="https://bookdown.org/" width="100%" height="550px"></iframe> --- ## rticles: <https://github.com/rstudio/rticles> The **rticles** package provides a suite of custom [R Markdown](https://rmarkdown.rstudio.com) LaTeX formats and templates for various formats, including: - [ACM](https://www.acm.org/) articles - [ACS](https://pubs.acs.org/) articles - [AMS](https://www.ametsoc.org/) articles - [Elsevier](https://www.elsevier.com) journal submissions - [IEEE Transaction](https://journals.ieeeauthorcenter.ieee.org/create-your-ieee-journal-article/authoring-tools-and-templates/tools-for-ieee-authors/ieee-article-templates/) journal submissions - [Sage](https://uk.sagepub.com/en-gb/eur/manuscript-submission-guidelines) journal submissions - [Springer](https://www.springer.com/gp/livingreviews/latex-templates) journal submissions - [Frontiers](https://www.frontiersin.org/) articles - [Taylor & Francis](https://taylorandfrancis.com/) articles ..and [more](https://github.com/rstudio/rticles). --- ## distill: <https://rstudio.github.io/distill/> <iframe src="https://rstudio.github.io/distill/" width="100%" height="550px"></iframe> --- exclude: true ## Materials .pull-left70[ - **Yihui Xie, J. J. Allaire, and Garrett Grolemund. [R Markdown: The Definitive Guide](https://bookdown.org/yihui/rmarkdown/). Chapman & Hall/CRC, 2018.** - RStudio's [R Markdown "Get Started" Tutorial](https://rmarkdown.rstudio.com/lesson-1.html) - RStudio's [R Markdown Articles](https://rmarkdown.rstudio.com/articles.html) - **[R Markdown Gallery](https://rmarkdown.rstudio.com/gallery.html)** - **10-minute interactive [Markdown tutorial](https://www.markdowntutorial.com/)** - Hadley Wickham, and Garrett Grolemund. ["R for Data Science"](https://r4ds.had.co.nz/). O'Reilly, 2017. Chapters: - [R Markdown](https://r4ds.had.co.nz/r-markdown.html) - [R Markdown formats](https://r4ds.had.co.nz/r-markdown-formats.html) - [R Markdown workflow](https://r4ds.had.co.nz/r-markdown-workflow.html) - RStudio's [`rmarkdown` cheat sheet](https://github.com/rstudio/cheatsheets/raw/master/rmarkdown-2.0.pdf) - RStudio's [`rmarkdown` reference guide](https://www.rstudio.com/wp-content/uploads/2015/03/rmarkdown-reference.pdf) ] .pull-right30[ <img src="figures//04-rmarkdown_book.png" width="100%" /> ] ??? - reference --- ## Session info ``` ## setting value ## version R version 4.0.4 (2021-02-15) ## os Windows 10 x64 ## system x86_64, mingw32 ## ui RTerm ## language EN ## collate English_United States.1252 ## ctype English_United States.1252 ## tz Europe/Berlin ## date 2021-04-19 ``` <div style="font-size:80%;"> .pull-left[ <table> <thead> <tr> <th style="text-align:left;"> package </th> <th style="text-align:left;"> version </th> <th style="text-align:left;"> date </th> <th style="text-align:left;"> source </th> </tr> </thead> <tbody> <tr> <td style="text-align:left;"> countdown </td> <td style="text-align:left;"> 0.3.5 </td> <td style="text-align:left;"> 2021-03-16 </td> <td style="text-align:left;"> Github (gadenbuie/countdown@a544fa4) </td> </tr> <tr> <td style="text-align:left;"> dplyr </td> <td style="text-align:left;"> 1.0.5 </td> <td style="text-align:left;"> 2021-03-05 </td> <td style="text-align:left;"> CRAN (R 4.0.4) </td> </tr> <tr> <td style="text-align:left;"> DT </td> <td style="text-align:left;"> 0.17 </td> <td style="text-align:left;"> 2021-01-06 </td> <td style="text-align:left;"> CRAN (R 4.0.3) </td> </tr> <tr> <td style="text-align:left;"> ggplot2 </td> <td style="text-align:left;"> 3.3.3 </td> <td style="text-align:left;"> 2020-12-30 </td> <td style="text-align:left;"> CRAN (R 4.0.3) </td> </tr> </tbody> </table> ] .pull-right[ ] </div> --- class: last-slide, center, bottom # Thank you! Questions? .courtesy[📷 Photo courtesy of Stefan Berger]