Skip to contents

Introduction

This vignette contains information about using R Markdown and knitr.

An R Markdown file (.Rmd) is a plain-text file with R code and markup. The markup is written in markdown. The R package rmarkdown converts R Markdown files to a single output file containing the R code, output of the R code, and additional text.

The rmarkdown package requires either Pandoc or RStudio (which already includes Pandoc) to convert R Markdown files to an html-file.

The rmarkdown package requires a LaTeX distribution, such as MikTex or TinyTeX (for debugging see here), to convert R Markdown files to a PDF. See the ‘R markdown cookbook’ and the ‘Definitive guide’ (both mentioned at Useful resources below) for extensive help. When installing MikTex as LaTeX distribution, set install for all users and always install missing packages on the fly (for all users), see this Stack Exchange post.

For TinyTeX:

writeLines(c(
  '\\documentclass{article}',
  '\\begin{document}', 'Hello world!', '\\end{document}'
), 'test.tex')
tinytex::pdflatex('test.tex')
options(tinytex.verbose = FALSE)

Useful resources

Global Settings for knitr used by R Markdown

For a list of available options, see str(knitr::opts_chunk$get()) and the overviews at the maintainer’s website (here and here).

The option echo = FALSE hides code from the output. Use numeric values to include the code of particular chunks. To collect all code as an the appendix at the end of of a document, see the section about putting code in an appendix from the ‘rmarkdown cookbook’.

If the option include = FALSE is used, code and results are not included in output, but code is executed such that its results can be used in other code chunks (useful as option for particular chunks, not as global option).

If the option error = TRUE is used, code execution will not stop on error (unless include = FALSE), but instead the error message is included in the output. This is useful in non-interactive use in production settings. If the option error = FALSE is used, code execution stops on error, which makes more sense in interactive use during development of the script.

Loading files

Files that have to be used by the R Markdown script (e.g., R scripts that are sourced, data files that are read) should be placed in the same directory as the R Markdown file, because the working directory when evaluating R code chunks is the directory of the input document by default. The working directory can be changed using opts_knit$set(root.dir = ...) but should not be changed using setwd(), see the Note in help("knit", package = "knitr").

An inferior alternative to including file = ... in the header is including

source("<path/to/file>.R", local = knitr::knit_global(),
       echo = TRUE, max.deparse.length = 1000)

in the body of the chunk. That method has the disadvantages that bare source code is included in the knitted file without the accompanying comments, that specification of the environment through the argument local can be error-prone and that max.deparse.length within source(...) has to be increased to ensure that all of the source code is printed (see help("source")).

Knitting documents to HTML and PDF

The following lines can be used to knit documents (i.e., generate output in HTML or PDF files containing the script with its output and additional text) containing a file name including a time-stamp. Using this way of creating documents creates and keeps local R objects in the current environment. Although that can be useful for inspection and debugging, the potential use of local objects can lead to non-reproducibility issues, such that the environment should be cleared before using it and final files should be created by knitting (e.g., using the Knit button in RStudio), not by using rmarkdown::render() (see here).

DateTimeStamp <- format(Sys.time(), format = "%Y_%m_%d_%H_%M")
rmarkdown::render("FilenameRMarkdownFile.Rmd", output_format = "html_document",
                  output_file = paste0("Filename", DateTimeStamp, ".html"),
                  output_dir = "./knitteddocs")
rmarkdown::render("FilenameRMarkdownFile.Rmd", output_format = "pdf_document",
                  output_file = paste0("Filename", DateTimeStamp, ".pdf"),
                  output_dir = "./knitteddocs")

Adding and collecting code chuncks

Add a new chunk by either (1) clicking the Insert Chunk button on the toolbar, (2) pressing Ctrl+Alt+I, or (3) typing the delimiters ```{r} above and ``` below the code chunk.

To collect all chunks in a R Markdown document that contain R code in a conventional R script use knitr::purl("FilenameRMarkdownFile.Rmd", documentation = 0).

Note that the various R Markdown options are not incorporated in such an R script, which might hamper exactly reproducing the analyses as executed when running the R Markdown file, see the note in help("purl", package = "knitr").

Formatting in R Markdown

Italic and bold text

Using *italic words* and _also italic words_ or **bold words** or even
_An **italic and bold phrase** in italic text_

is rendered as:

Using italic words and also italic words or bold words or even An italic and bold phrase in italic text

Partially bold text does not work inside link text in R <= 4.1.0.

Code chunks

R code chunks can be shown with or without its output through argument eval (which is TRUE by default):

```{r code-chunk-example}
sum(c(1, 2))
mean(c(1, 2))
```

shows a code chunk with its output, like:

sum(c(1, 2))
## [1] 3
mean(c(1, 2))
## [1] 1.5

Whereas

```{r code-chunk-example-no-output, eval = FALSE}
sum(c(1, 2))
mean(c(1, 2))
```

shows a code chunk without its output, like:

sum(c(1, 2))
mean(c(1, 2))

Table

| Name       | Description                      |
| :--------- | :--------------------------------|
| `Name one` | Some description                 |
| `Name two` | Some description                 |

gives:

Name Description
Name one Some description
Name two Some description

Lists

Lists need an empty line before the first item to be correctly rendered. Sub-items are created by indenting them. Numbered lists (ordered lists) are created by using a number followed by a dot (1.). Non-numbered lists (non-ordered lists) are created by using asterisks (*), plus signs (+), or dashes (-).

non-numbered list:

* item one
* item two
  * sub-item one
  * sub-item two

numbered list:

1. item one
2. item two

These lists would render as:

non-numbered list:

  • item one
  • item two
    • sub-item one
    • sub-item two

numbered list:

  1. item one
  2. item two

Escaping

To include n delimiters (`) in the output, escape them by enclosing with n + 1 delimiters:
for example, `` `some text` `` produces `some text`, and ``` `` `some text` `` ``` produces `` `some text` ``. Do not start a line of code with a delimiter if you want to escape other delimiters: that would be interpreted as starting a code section.

To include code to create code chunks (i.e., include code which escapes chunk headings), use

r ''````{r use-sum}
1 + 2
```

to show how to create a code chunk like

1 + 2
## [1] 3