https://rmarkdown.rstudio.com/
“R Markdown provides an unified authoring framework for data science, combining your code, its results, and your prose commentary. R Markdown documents are fully reproducible and support dozens of output formats, like PDFs, Word files, slideshows, and more.” - R for Data Science
R Markdown lets you organize your work, keep it all in one place, avoid confusion, and save time.
Scientists have been keeping “science journals” for centuries. R Markdown is your tool for keeping your own ‘research notes’, documenting your learning, attempts, failures, and successes.
Like all good mad scientists do.(Image from https://www.bershad.com/pgg/frank-front.gif)
Before we talk about using markdown, I have some wisdom to share with you, which I earned through suffering and tears; When you are beginning a new project (i.e. a research study, a class), ALWAYS do the following:
File -> New File -> R Notebook
An R markdown notebook contains 3 different components:
Let’s look at each one of these parts in turn.
The YAML header appears at the top of the document. This is the first part you should edit when you create a document.
In it’s most basic form, the header looks something like this:
---
author: "Steven Luke"
title: "R Markdown Example"
subtitle: "Psych 312R: Intro to R"
date: "`r Sys.Date()`" # Uses the current data when you generate the document
---
What kind of document do you want to create? Basic options include:
# output:
# html_notebook:
# toc: true
# html_document: # If you want to be able to export as HTML
# toc: true
# pdf_document: # If you want to be able to export as PDF
# toc: true
# word_document: # If you want to be able to export as a Word Doc
# toc: true
The toc: true option adds a table of contents to the
document. If you don’t want that, change this to false.
There are other formatting options you can add to the document after
toc: true, such as:
toc_float: true - should the table of contents stay on
screen as you scroll (for HTML only)number_sections: true - should the different sections
be numbered?code_folding: show - should there be a button to hide
all the code? (or code folding: hide starts with the code
hidden, but offers a button to make it appear)theme: paper - change how the document looks by
applying a theme. There are several built-in themes besides paper: https://www.datadreaming.org/posts/2018-04-11-r-markdown-theme-gallery/2018-04-11-r-markdown-theme-gallery.htmlAnd of course there are more formatting options that exist if you want to explore them.
We’ll discuss this in more detail below.
In your R Markdown document, create a YAML header that:
Double check your header for errors - the YAML header is REALLY sensitive to both typos and spacing.
With R Markdown, you can put your text right into the .rmd document, where it peacefully co-exists with your code. You can create a full document with sections, sub-sections, paragraphs, bulleted lists, etc. You can also include links, tables, images, even embedded videos!
Regardless of the purpose of your project, you want to surround your code with text. The way you use text will depend on your goals:
To create a header use a hashtag (#). More hashtags changes the header level.
# Level 1 Header
## Level 2 Header
### Level 3 Header
#### Level 4 Header
##### Level 5 Header
Some basics of text formatting:
Italics – *italic* or
_italic_
Bold – **bold** or
__bold__
Superscript – ^Super^script
Subscript – ~Sub~script
Make sure to have an empty line before the start of any list.
Use *. Indent for sub-items.
* Item 1
* Item 2
* Sub-item 2-1
Use 1. Sub-items don’t work here.
1. Item 1
1. Item 2
Note that you don’t have to increment the number - R does this for you!
http://example.com -
<http://example.com>
Link to Nowhere -
[Link to Nowhere](http://example.com)

This is a table:
| First Header | Second Header |
|---|---|
| Content Cell | Content Cell |
| Content Cell | Content Cell |
To make this table, do this:
# | First Header | Second Header |
# | :----------: | ------------- |
# | Content Cell | Content Cell |
# | Content Cell | Content Cell |
Some things to notice:
| Left | Center | Right |
|---|---|---|
| 1 | 2 | 3 |
| 4 | 5 | 6 |
You can (and should) include R code in your document in 2 different ways:
To add a code chunk, you can
The new code chunk should look something like this (highlighted in red):
Image from https://smac-group.github.io/ds/images/rmd_code_chunk.png
Notice some things about a code chunk.
At the start of each R Markdown document, there should be a unique chunk called setup (see image above). Code in this chunk will always run when any other code in the document runs. That makes this a great place to install and load packages! You can also set global options for all code chunks in the document here. Below is an example setup chunk you could use:
#````{r setup}
#knitr::opts_chunk$set( # Sets options for all code chunks in document
# echo = TRUE, # All code chunks should be visible
# message = FALSE, # Messages should not appear in output
# warning = FALSE # Warnings should not appear in output
#)
#library(tidyverse) # Automatically loads the tidyverse package
#```
Note that you don’t have to type knitr:::opts_chunk...
and all that. Just use the gear on the right of the setup chunk to
select the options you want.
Sometimes you want code to appear in line with your text, like so:
My opponent is an extremist who would have you believe that 2 + 2 is {insert r code here}.
In-line code looks like this: `r 2 + 2`
So the whole line would look like this:
My opponent is an extremist who would have you believe that 2 + 2 is `r 2 + 2`.
And the output would look like this:
My opponent is an extremist who would have you believe that 2 + 2 is 4.
In-line code is useful when you:
`r studentlist[6]`.`r mean(testscores)`.One excellent way to use in-line code is in tables:
testscores <- c(84, 56) # Make a vector with 2 scores
names(testscores) <- c("Tim", "Wilhelm") # Give each score a name of a student
| Student | Score |
|---|---|
`r names(testscores)[1]` |
`r testscores[[1]]` |
`r names(testscores)[2]` |
`r testscores[[2]]` |
This produces:
| Student | Score |
|---|---|
| Tim | 84 |
| Wilhelm | 56 |
This lets me make a table without having to remember all the details. And if the students’ names and scores change, I can use the same table!
Seems a bit intimidating? Don’t worry, you’ll get it!
Another way to use in-line code is in text, like so:
I thought that
`r names(testscores)[2]`was smarter than`r names(testscores)[1]`, but`r names(testscores)[1]`got a`r testscores[[1]]`on the test and`r names(testscores)[2]`only got a`r testscores[[2]]`!
This produces the following:
I thought that Wilhelm was smarter than Tim, but Tim got a 84 on the test and Wilhelm only got a 56!
This is useful for making reusable APA-style paragraphs that contain the results of your statistical analyses - without having to type out those results. R fills it in for you!
Don’t forget that you need to install and load the randomNames package. Use the setup chunk for this!
Here is a Markdown header formatted to produce an HTML document:
---
author: "Steven Luke"
title: "R Markdown Example"
subtitle: "Psych 312R: Intro to R"
date: "`r Sys.Date()`"
output:
html_document:
toc: yes #include a table of contents
---
Note the indentation and the colons.
Many more formatting options can be found here: https://bookdown.org/yihui/rmarkdown/html-document.html
Here is a Markdown header formatted to produce a PDF document:
---
author: "Steven Luke"
title: "R Markdown Example"
subtitle: "Psych 312R: Intro to R"
date: "`r Sys.Date()`"
output:
pdf_document:
toc: yes #include a table of contents
# other formatting options go here
---
Note the indentation and the colons used to ‘nest’ options
Many more formatting options can be found here: https://bookdown.org/yihui/rmarkdown/pdf-document.html
I have found that making PDFs is the most failure-prone. Two bits of advice:
tinytex::install_tinytex()Here is a Markdown header formatted to produce a word document:
---
author: "Steven Luke"
title: "R Markdown Example"
subtitle: "Psych 312R: Intro to R"
date: "`r Sys.Date()`"
output:
word_document:
toc: yes #include a table of contents
reference_docx: my-styles.docx # This coppies the formatting from an existing word document called 'my-styles.docx'
# other formatting options go here
---
Note the indentation and the colons used to ‘nest’ options
Also note the use of reference_docx: my-styles.docx.
This is a handy way to copy the styles from an existing word document to
the document you are creating. So, if you already have a word document
with APA-style headers, tables, etc., you can use that to create
more.
(Bonus) Make an APA-style Word document
Here is a Markdown header formatted to produce a word document:
---
author: "Steven Luke"
title: "R Markdown Example"
subtitle: "Psych 312R: Intro to R"
date: "`r Sys.Date()`"
output:
powerpoint_presentation:
toc: no #include a table of contents
reference_doc: my-styles.pptx
slide_level: 2
# other formatting options go here
---
Note the indentation and the colons used to ‘nest’ options
Also note the use of reference_doc: my-styles.pptx. This
is a handy way to copy the styles and layout from an existing powerpoint
to the presentation you are creating.
Also note slide_level: 2. This breaks up the text into
slides at the level 2 headers. You can change this to be higher or
lower. If you want to insert a slide break elsewhere, use
*** in your document.
(Bonus) Make a Powerpoint presentation
You can also use R Markdown to make
Let’s take a moment to review proper workflow:
When you are beginning a new project (i.e. a research study, a class), ALWAYS do the following:
Now that you know about R Markdown, let’s talk about how to use it optimally. When you start with a new notebook, do the following:
As you work through your analysis, stay organized and keep notes :
Now that you’ve learned how to do things the hard way, take a moment to check out the Visual Tab. Notice in the top left of your R Markdown Notebook it says Source and Visual. Click on Visual. Now you’ve changed to something more familiar - the visual tab is more like Word or Google Docs. Do the following in the Visual Tab: