Data @ Reed

R Markdown

R Markdown is a document type that lets you mix plain writing and code to produce reports, assignments, and presentations using R. R Markdown is most useful when you want to integrate R output (like plots or tables) with commentary. You can open a blank R Markdown file within RStudio under File / New File / R Markdown, and then adjust settings as needed.

YAML and output

At the top of any R Markdown document is the YAML header. This section denotes general settings/metadata for the document, including

  • Title/Date/Author

  • Output method (html, pdf, .doc, GitHub file, etc.)

  • LaTeX packages included

  • Table of contents (y/n, settings)

The only one of these that you absolutely need is the output method. When you knit an R Markdown file to produce an output, R needs to know what type of file to produce.

Code

You can put R code into an R Markdown document, and the evaluated code results will appear in the output document.

R Markdown example picture

 

The “Insert” button at the top of the editor window will insert a blank code chunk for you, or you can define it manually with the three backticks ( ` , key to the left of the number 1 on your keyboard) at top and bottom as in the picture above.

Every chunk runs sequentially, so any objects that you create in an earlier chunk will be available for you to use in a later chunk. Note: A completely new R session is created when you run an Rmd file, so anything that you do not explicitly access in the document will not be available, and calling on it will throw an error.

Text formatting

In between code chunks, you can type plain text to put in the output document. The formatting style that R Markdown uses is called Markdown, which gives some basic text-editing features such as

  • Bold/italics/underline

  • Bulleted/numbered lists

  • Links

  • Headers

  • Equation formatting through LaTeX

For info on all of these formatting methods, see this cheatsheet on Markdown syntax. For more help with R Markdown, see this book chapter.