
Working with R Markdown allows you to create different types of reports, from static websites to PDFs and slides in R. Many of them come with templates, but also let you adjust for specific user needs. This makes R Markdown easy to use and an efficient way to turn data analyses into cohesive, high-quality reports.
With R Markdown you can create reproducible and shareable documentation. Users can create reports for evaluation by different pairs or through the community, following best practices such as GxP Compliance with R Markdown.
Are you looking for a multilingual version of R Markdown? Try Quarto, for interactive Markdown documents.
In this post, we’ll present the different types of formats that R Markdown can design and how to create them. We’ll also cover several tips and materials when working with each. Continue reading to master R Markdown.
- YAML and R Markdown
- Rendering Documents
- 1. Reading the documentation
- 2. Leverage Rstudio UI and package templates
- 3. Create your own templates
- 4. Separate the document into pieces
- 5. Using params
- 6. Extensions
R Markdown Reporting – Documents
The steps required to create R Markdown reports are set primarily by knitr and pandoc, but also other extensions such as latex with tinytex.
How many file formats can R Markdown render?
R Markdown can render formats from HTML docs, Notebooks, PDFs, Word docs, OpenDocument text, Rich text, Markdown variants, vignettes – and that’s just covering documents some more include:
- html_document – HTML document w/ Bootstrap CSS
- pdf_document – PDF document (via LaTeX template)
- word_document – Microsoft Word document (docx)
- md_document – Markdown document (various flavors)
- ioslides_presentation – HTML presentation with ioslides
- revealjs::revealjs_presentation – HTML presentation with reveal.js
- slidy_presentation – HTML presentation with W3C Slidy
- powerpoint_presentation: PowerPoint presentation
- flexdashboard::flex_dashboard – Interactive dashboards
- tufte::tufte_html – HTML handouts in the style of Edward Tufte
- html_vignette – R package vignette (HTML)
- github_document – GitHub Flavored Markdown document
It is worth mentioning that R Markdown knitr can execute code in other languages besides R, including:
- Python
- SQL
- Julia
- JavaScript
- CSS
If you’re searching for a specific language, search the knitr repository for the [language] + “engine.”
Looking to step up your presentations with R? See how easy it is to create PowerPoint Presentations with R Markdown.
YAML and R Markdown
In order to define which type of document the report will result in, knitr requires metadata that states the output format. This is done in the YAML header of the R Markdown file:
YAML contains a set of arguments that each document can have. Even different packages can have their own set of rules that can be adjusted through the YAML component
It usually is set on the header of the R Markdown document but can also be used as a separate file.
YAML is an extensible approach to metadata. That means that any metadata that is incorrect will fail silently. This may cause issues in passing the correct information or what is available by the package.
Because of this, ymlthis is a package that gathers the most common approaches when setting YAML for R markdown documents. It contains a yaml fieldguide that shares the most common sources of YAML.
The ymlthis addon saves a lot of time when setting up the YAML configuration. This is possible because it has a set of the most common configuration for many types of well-known documents:
Rendering Documents
It should be clear by now that changing the type of document is basically changing the YAML option to be run. In most cases, this will be more than enough and Rstudio provides a brief summary of the required approach on their cheatsheet and R Markdown reference:
R Markdown Reporting Best Practices
Because R Markdown has a lot of flexibility, some guidelines and best practices can help improve productivity and reduce common errors. If you want to be an R Markdown expert, start with these best practices:
1. Read the documentation first
This may seem straightforward, but the truth is: There is no better place to understand the appropriate metadata and design of the markdown document than with the maintainer. For packages that are so well adopted like R Markdown, most common issues and expected behavior are already documented.
Save time and headaches by going to the source.
2. Leverage Rstudio UI and package templates
When rendering new R Markdown documents, you can use templates from Rstudio UI and leverage the options that new packages can have. You can see an example view here:
3. Create your own templates for R Markdown
Making your own templates will boost your productivity and keep you with steady-state documents.
This can be used through many types of documents such as word documents or even HMTL documents, including slides, by setting your own HTML and/or CSS template.
Bslibs is a great resource when setting the UI design since it allows you to dynamically set the CSS components:
4. Separate the document into different pieces
This is not only important to make your code cleaner but also reusable. Let’s take the {xaringan} package as an example:
---
title: "R Markdown examples"
author: "Author"
date: "`r Sys.Date()`"
output:
xaringan::moon_reader:
css: xaringan-themer.css
params:
data: !r mtcars
variable: "Species"
always_allow_html: true
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(GGally)
library(xaringanExtra)
library(DT)
library(skimr)
library(knitr)
library(png)
library(leaflet)
```
```{r, child="preamble.Rmd"}
```
```{r xaringanExtra-clipboard, echo=FALSE}
xaringanExtra::use_clipboard()
xaringanExtra::use_tile_view()
xaringanExtra::use_editable(expires = 1)
xaringanExtra::use_scribble()
xaringanExtra::use_search(show_icon = TRUE)
xaringanExtra::use_fit_screen()
xaringanExtra::use_clipboard()
xaringanExtra::use_tachyons()
```
```{r xaringan-themer, include=FALSE, warning=FALSE}
library(xaringanthemer)
style_mono_accent(
base_color = "#1a317e",
header_font_google = google_font("Josefin Sans"),
text_font_google = google_font("Montserrat", "300", "300i"),
code_font_google = google_font("Fira Mono")
)
```
Separating the required components of the {xaringan} into a different document makes it reusable and easier to change any behavior regarding the slide components.
It also creates a better understanding of the workflow such as in the example of using {pins} with R Markdown.
Additionally, you can set conditional behaviors that change the workflow of the report like the Conditional Emails with RStudio Connect.
5. Using params in R Markdown
Params allow you to dynamically change the parameters of the R Markdown document when you knit:
This adds a new layer to R Markdown flexibility. Using params allows you to have a reactive component as input for Shiny development:
library(shiny)
library(rmarkdown)
ui = fluidPage(
textInput("user", "Name"),
downloadButton("markdown", "Get report")
)
server <- function(input, output, session) {
output$markdown <- downloadHandler(
filename = "RMD_report.html",
content = function(file) {
params <- list(name = input$user)
rmarkdown::render(
"./report.rmd",
output_file = file,
params = params,
envir = new.env(parent = globalenv())
)
}
)
}
shinyApp(ui, server)
---
title: "Hello, world!"
output: html_document
params:
name: "User"
---
```{r}
params$name
```
6. Extensions in R Markdown
There are a variety of extension options when we’re working with R Markdown. We’ve collected a few and below is a small summary of information from use cases and materials:
Type | Summary | Link |
YAML Header | Markdown variants documents | R Markdown: The Def. Guide |
Code Chunks | Convert models to equations | R Markdown Cookbook |
Code Chunks | Control the width of text output | R Markdown Cookbook |
Code Chunks | Control the size of plots/images | R Markdown Cookbook |
Code Chunks | Figure alignment | R Markdown Cookbook |
Code Chunks | Verbatim code | R Markdown Cookbook |
Code chunks | Embed a web page | R Markdown Cookbook |
Code Chunks | Conditional chunks | R Markdown Cookbook |
Formatted text | Multi-column layout | R Markdown Cookbook |
Formatted text | Code results with appropriate layout PDF | Introduction to R |
Formatted text | Suppress loading packages on Rmd | Introduction to R |
Formatted text | Choose a variety of fonts from google | Google Fonts |
Packages | Template ready HTML documents | Rmdformats |
Packages | Template ready HTML documents | Prettydoc |
Packages | Colaborate Rmd on Google Drive | trackdown |
Packages | Research project as a website | workflowr |
Packages | Send emails based on R Markdown | blastula |
Concluding R Markdown Reporting Tips
In this blog post, we discussed some of the best practices when working with R Markdown documents. You’ve learned a few best practices including::
- Always reading the documentation first (trust me, it’s worth it)
- Leverage Rstudio UI and package templates
- Create your own templates
- Separate the document into different pieces
- Use params
Looking for more tips? Check out these tips for code, images, comments, and tables in R Markdown.
There are plenty of amazing things you can achieve with R and R Markdown. But it’s important to keep reusability and adoption in mind. Be sure to stay consistent and write durable r code and production-ready code that will last.
These will help you not only become an R Markdown wiz but a better overall R developer!
What are your favorite practices to follow when working with R Markdown? Let us know in the comments or tag us on Twitter.