This template illustrates the basics of an R Markdown document (aka. ‘RMarkdown’ or just ‘Markdown’). R Markdown documents have the .Rmd file extension. The .Rmd source file of this document is available here.

Creating an R Markdown document

In order to use R Markdown, you need to have (or install) and load the rmarkdown and knitr packages in R:

# Install required packages (always):
# install.packages("tidyverse", "ds4psy")

# Load required packages (always):

Markdown documents are documents that combine text and code. They are saved as simple text documents (with the file extension .md or .Rmd) and can be edited by any text editor — ideally by a program that interacts with R (like RStudio).

You can create a new RMarkdown document in RStudio by clicking File > New File > R Markdown. At the top of a new file, you will see inputs for a page title, author, date, and the output format. Change the title, author, and date to suit your current document.

Text vs. R code

Markdown separates regular text from R code. Unless you use a code chunk, Markdown will treat all your text as regular text. For example, when we write the following lines:

2 + 2 hist(ChickWeight$weight)

Markdown just thinks that we’re writing text, not R code. (Actually, it even prints consecutive lines of text into the same line unless a line of text ends with two spaces.)

Formatting Text

Italics, bold, and headers

To write text in italics font, use a single underscore (or asterix) before and after the text.

To write text in bold font, use a double asterix (or underscores) before and after the text.

1st-Level Header

To make headers in Markdown, use the # (i.e., pound symbol) at the beginning of a line.

Note that non-function words of 1st-level headings tend to be capitalized (in APA format).

2nd-level header

Multiple pound symbols indicate lower-level headers.

3rd-level header

Note that, in an actual text, there should be at least two headings on every level.

Making Lists

To create a numbered list of items, just use numbers before paragraphs:

  1. First element
  2. Second element
  3. Third element

To create a non-numbered bullet list, use a single dash or asterix before a list of paragraphs:

  • First element of bullet list.
  • Second element of bullet list.
    • 1st sub-element
    • 2nd sub-element
  • Third element of bullet list.

Note that you can create multiple levels of lists, using leading spaces to indicate the level.

Including R Code Chunks

To evaluate R code in a Markdown document, you need to enclose the R code into a code chunk. Here’s how a code chunk looks:

# This is a code chunk. Everything included here will be interpreted as R code.
# (Specifying a unique chunk_name helps to keep track of your chunks later.) 

# R will evaluate the code in this chunk and print the result:
2 + 2
## [1] 4

As you can see, code chunks in RStudio are highlighed with a gray background. Everything you put in this chunk will be evaluated by R Markdown as R code when you knit the document.

You can insert a new code chunk in one of three ways:

  1. Use the Command-Alt-I shortcut on a Mac.

  2. Click the “insert new code chunk” button on the top right hand of this panel. It looks like a green square with an arrow.

  3. Copy and paste an existing chunk and change its content and properties.

R Code Chunk options

You can add arguments at the start of code chunks to change how the code included in the chunk is evaluated and presented. Here are the most common options:

Setting echo = FALSE

By default, Markdown will repeat (aka ‘echo’) your R code in your final output. However, if you don’t want this, you can add the echo = FALSE argument.

In the following code, I will write some comments and calculate the mean weight of chickens in the ChickWeight dataset. Because I include the echo = FALSE argument at the top of the chunk, the chunk will only print the result in the final output, not the original R code that generates the result:

## [1] 121.8183

By contrast, if you do not include the echo = FALSE argument or set echo = TRUE, R will print the original code AND the result:

# Now R will copy this code (including comments) and print the result 
# because this chunk did not set the option echo = FALSE.

# What is the mean weight of chickens?
## [1] 121.8183

Setting eval = FALSE

If you include the eval = FALSE argument, R will NOT evaluate code in a chunk:

# Setting eval = FALSE at the beginning of this chunk, R will NOT evaluate the code. 
# However, because we did not include echo = FALSE, it will still print this code and comment: 
1 + 1

When setting both echo = FALSE, and eval = FALSE, R will neither copy nor evaluate the code:

Specifying fig.width and fig.height

If you generate a plot in a chunk, you can change its size with the fig.width and fig.height options:

The following chunk will print a small figure as I set fig.width = 4 and fig.height = 3 (in inches):


The following chunk will print a tall and narrow figure as we set fig.width = 4, fig.height = 7:



In addition to creating regular code chunks, you can create minichunks that go directly into your text.

A minichunk looks like this: 4 and is evaluated in the output document (i.e., you’ll only see the result of the minichunk).

For example, we can write: “The mean weight of chickens was 122.” When the document is created, R will evaluate the R code in the mini-chunk and replace it with the result of the corresponding R command in the output document.

Once an object has been defined, you can use it later in both regular chunks and in minichunks. For instance, let’s create a chunk that defines several objects (specifically diet.1.mean, diet.4.mean, etc.) which calculate descriptive statistics of chickens on different diets from the ChickWeight dataframe:

diet.1.mean <- round(mean(ChickWeight$weight[ChickWeight$Diet == 1]), 2)
diet.4.mean <- round(mean(ChickWeight$weight[ChickWeight$Diet == 4]), 2) <- round(sd(ChickWeight$weight[ChickWeight$Diet == 1]), 2) <- round(sd(ChickWeight$weight[ChickWeight$Diet == 4]), 2)

Once the objects were defined and have been evaluated, we can use them in a minichunk:

  • “We measured the weight of several chickens on different diets. The chickens in diet 1 had a mean weight of 102.65 (SD = 56.66). By contrast, chickens on diet 4 had a mean weight of 135.26 (SD = 68.83).”

Knitting a Document

To create an HTML (or Word or Latex) document from a Markdown (.Rmd) document, you need to knit the document. Knitting a document simply means taking all the text and code and weaving (or knitting) it into a nicely formatted document. Fortunately, the R’s knitr package takes care of the hard parts.

To knit a document (into html, LaTeX pdf, or – if necessary – MS Word) from your .Rmd file, do one of the following:

  1. on a Mac: Use the Command-Shift-K keyboard shortcut;

  2. Click the “Knit” button at the top of this window. (Its icon typically shows a ball of yarn.)

Loading libraries

If you use a package in your code, you must explicitly load the package in your Markdown document using library() before using the package. If you don’t, Markdown may not know which packages you are using and the code won’t work.

# When requiring additional packages, you should ALWAYS load them explicitly 
# at the beginning of your markdown document: 

Warning: R code with any errors will not knit!

If your R code (in any standard chunks or minichunks) contains R errors, the document will not knit.

For example, the following chunk has a syntax error. If we tried to knit this document with eval = TRUE, we would get an error message:

# This text is commented and NOT evaluated --- we can write whatever we want here: x <- 0/0!

This text is NOT commented, R thinks it is R code and will freak out if we try to knit the document.
Thankfully, we included the eval = FALSE argument for this chunk, so R will just ignore it.

If your document fails to knit, you need to go through your code chunk by chunk to find and fix the error.


[Updated on 2020-05-10 by hn.]