R Markdown Reporting Best Practices

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. 

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:

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()`"
    css: xaringan-themer.css
  data: !r mtcars
  variable: "Species"
always_allow_html: true

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)

```{r, child="preamble.Rmd"}


```{r xaringanExtra-clipboard, echo=FALSE}
xaringanExtra::use_editable(expires = 1)
xaringanExtra::use_search(show_icon = TRUE)


```{r xaringan-themer, include=FALSE, warning=FALSE}
  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:


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)
        output_file = file,
        params = params,
        envir = new.env(parent = globalenv())

shinyApp(ui, server)

title: "Hello, world!"
output: html_document
  name: "User"

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:

YAML HeaderMarkdown variants documentsR Markdown: The Def. Guide
Code ChunksConvert models to equationsR Markdown Cookbook
Code ChunksControl the width of text outputR Markdown Cookbook
Code ChunksControl the size of plots/imagesR Markdown Cookbook
Code ChunksFigure alignmentR Markdown Cookbook
Code ChunksVerbatim codeR Markdown Cookbook
Code chunksEmbed a web pageR Markdown Cookbook
Code ChunksConditional chunksR Markdown Cookbook
Formatted textMulti-column layoutR Markdown Cookbook
Formatted textCode results with appropriate layout PDFIntroduction to R
Formatted textSuppress loading packages on RmdIntroduction to R
Formatted textChoose a variety of fonts from googleGoogle Fonts
PackagesTemplate ready HTML documentsRmdformats
PackagesTemplate ready HTML documentsPrettydoc
PackagesColaborate Rmd on Google Drivetrackdown
PackagesResearch project as a websiteworkflowr
PackagesSend emails based on R Markdownblastula

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.