17.2 R Markdown
Markdown is a simple markup language for text formatting. R Markdown (Xie, Allaire, and Grolemund 2018) is an extension of Markdown, which makes it easy to combine plain text, R code, and the output of R code in one document. This makes R Markdown an extremely helpful tool to report our analyses. Using R Markdown we can create HTML or PDF files containing all code used in our analyses, the output we get from the code, and detailed text explaining what we did in each analysis step. It is very easy to build R Markdown files in RStudio. Simply click on the white symbol with the green plus sign in the upper-left corner of your RStudio window. Then, in the dropdown menu, click on “R Markdown…”.
After defining the name of your new R Markdown document, it should pop up in the upper-left corner of your window.
The file already contains some exemplary content, which we can delete, except for the first six lines:
--- title: "Analysis" author: "Mathias Harrer" date: "10/16/2019" output: html_document ---
This part is your so-called YAML header. It controls the title, author, date and export format of your document. The
output format I chose for my document is
html_document, meaning that the document will be exported as a HTML page once it is rendered. The structure of the R Markdown document consists of two parts: plain Markdown text, and so-called R chunks, shown in grey. We will not go into detail how the text parts in the R Markdown document are formatted, but this Cheat Sheet should be a great resource to start learning the Markdown syntax (this should only take about twenty minutes). The R code chunks, on the other hand, simply contain all the R code you would usually type into your Console. By clicking on the “Insert” field on the upper-right corner of the document, you can add new code chunks yourself.
The code in the chunks works just like regular R code, except that the output is not displayed in the Console or Plots pane, but directly in the document. To run one of the chunks, you can click on the little green triangle next to each chunk.
Once we finished our document, we can export it as an HTML (or PDF, or MS Word document) by clicking on the “Knit” symbol in the upper-right corner. This will render the document, including all text, code, and ouput, and export it in the defined format. The finished document will automatically be saved in your project folder.
This has been an ultra-brief introduction into R Markdown, which contains much more functionality to explore. To learn more about R Markdown, you can consult the comprehensive online guide.
Xie, Yihui, Joseph J Allaire, and Garrett Grolemund. 2018. R Markdown: The Definitive Guide. Chapman; Hall/CRC.