Creating content with R Markdown

A brief tutorial

Matthew Crump

10/31/2019

What is R Markdown?

Let’s take the R Markdown quick tour from RStudio https://rmarkdown.rstudio.com/authoring_quick_tour.html

The definitive R Markdown guide

For a comprehensive guide to R Markdown see the definitive guide:

https://bookdown.org/yihui/rmarkdown/

R Markdown and reproducible science

Creating a new R Markdown document from RStudio

Example: Reproducible analysis with R Markdown

Goals:

  1. Create a new R markdown document
  2. Load some data
  3. Show a figure, and report some descriptive statistics

R Markdown details

  1. YAML Front Matter
  2. Setup Chunk
  3. R code snippets
  4. Code snippet knitr options
  5. Tips and tricks

YAML Front matter

“YAML Ain’t Markup Language”

YAML is used to declare global parameters for the document.

This often includes title, author, bibliography files, and output formats.

There may be many more parameters depending on the template file used for the R Markdown document.

Setup chunk

Set defaults for all R code chunks in setup chunk at the beginning

Defaults can be modified for individual chunks later on.

  • echo = FALSE, prevents displaying R output
  • warning = FALSE, prevents printing of R warnings
  • message = FALSE< prevents printing of R messages (e.g., fairly common when loading some packages)
  • fig.align = “center”, all figures will be center aligned
  • cache = FALSE, turns off caching of results
  • out.width = “100%”, figure width is 100% of screen

R Code snippets

  1. Correctly defined code-chunks appear in a grey-box
  2. Option-command-I to automatically create chunk in R Studio (Ctrl-Alt-I on PC)
  3. Press play button to run the chunk. Output appears below the chunk in the editor window.

Anatomy of a code chunk

Knitr output options

knitr is the engine that converts .Rmd files to other file types. Each R code chunk is processed by knitr, and can take on options to control outputs.

knitr figure output options

The following setup options are useful for figure output.

Knitting (press knit to compile your document)

IMPORTANT KNITTING INFO

  1. Knitting is done in a separate R session behind the scenes
  2. Code snippets are compiled in order from top-to-bottom
  3. Knitting can be automated with the knitr::render() function, pressing the knit button in RStudio is a built-in way to call the render function for the current document.

Why won’t this knit?

Pressing the play button might show the graph, but compiling fails when knitting the document?

  1. the call to ggplot() occurs in chunk 1 before the package is loaded in chunk 2, causing an error.
  2. The ggplot2 package may be loaded in the current R session, allowing it to run the first chunk.

Assorted info

Multi column