5.1 RMarkdown

The RMarkdown framework makes it very easy to create nice reports from R code in RStudio.

Here are the basics of opening and rendering an R Markdown file in RStudio:

  • To open a new R Markdown file, go to “File” -> “New File” -> “RMarkdown…”. In the box that pops up, chose a “Document” in “HTML” format.
  • This will open a new R Markdown file in RStudio. The file extension for R Markdown files is “.Rmd”.
  • The new file comes with some example code and text. You can run the file as-is to try out the example. You will ultimately delete this example code and text and replace it with your own.
  • Once you “knit” the R Markdown file, R will render an HTML file with the output. This is automatically saved in the same directory where you saved your .Rmd file.
  • Write everything besides R code using Markdown syntax (explained below).

To include R code in an RMarkdown document, you need to separate off the code chunk using the following syntax (here, the code assigns the numbers one to 10 to the object my_vec):

my_vec <- 1:10

This syntax might look unusual, but it tells R how to find the start and end of pieces of R code when the file is processed by R. R will walk through, find each piece of R code inside these special sections, run it and create output (printed output or figures, for example). R will ignore anything not in one of these sections, including the text of the report. The output from this R processing will then pass into another program to complete rendering (e.g., a LaTeX engine for pdf files).

R Markdown files are mostly written using Markdown. To write R Markdown files, you need to understand what markup languages like Markdown are and how they work.

In Word and other word processing programs you have used, you can add formatting using buttons and keyboard shortcuts (e.g., “Ctrl-B” for bold). The file saves the words you type. It also saves the formatting, but you see the final output, rather than the formatting markup, when you edit the file (WYSIWYG – what you see is what you get).

In markup languages,30 Examples include HTML, LaTeX, and Markdown on the other hand, you markup the document directly to show what formatting the final version should have (e.g., you type **bold** in the file to end up with a document with bold).

To write a file in Markdown, you’ll need to learn the conventions for creating formatting. This table shows the markup for some common formatting choices:

Code Rendering Explanation
**text** text boldface
*text* text italicized
[text](www.google.com) text hyperlink
# text first-level header
## text second-level header

Some other simple things you can do in Markdown include:

  • Lists (ordered or bulleted)
  • Equations
  • Tables
  • Figures from file
  • Block quotes
  • Superscripts

See the resources listed in “Learn More” for links to some helpful resources for learning RMarkdown, including more of these Markdown formatting mark-ups.