rmarkdown :: Cheatsheet (2024)

rmarkdown :: Cheatsheet (1)

Download PDF

Translations (PDF)

  • Dutch
  • German
  • Italian
  • Japanese
  • Korean
  • Spanish
  • Turkish
  • Vietnamese

What is rmarkdown?

  • .Rmd files: Develop your code and ideas side-by-side in a single document. Run code as individual chunks or as an entire document.
  • Dynamic Documents: Knit together plots, tables, and results with narrative text. Render to a variety of formats like HTML, PDF, MS Word, or MS PowerPoint.
  • Reproducible Research: Upload, link to, or attach your report to share. Anyone can read or run your code to reproduce your work.

Workflow

  1. Open a new .Rmd file in the RStudio IDE by going to File > New File > R Markdown.

  2. Embed code in chunks. Run code by line, by chunk, or all at once.

  3. Write text and add tables, figures, images, and citations. Format with Markdown syntax or the RStudio Visual Markdown Editor.

  4. Set output format(s) and options in the YAML header. Customize themes or add parameters to execute or add interactivity with Shiny.

  5. Save and render the whole document. Knit periodically to preview your work as you write.

  6. Share your work!

Source Editor

rmarkdown :: Cheatsheet (3)

Features within the Source Editor

  1. New File
  2. Embed Code
  3. Write Text
  4. Set Output Format(s) and Options
  5. Save and Render
  6. Share
  • Set preview location
  • Insert code chunk
  • Go to code chunk
  • Run code chunk(s)
  • Show outline
  • Modify chunk options
  • Run all previous chunks
  • Run current chunk
  • Switch to visual editor

Visual Editor

rmarkdown :: Cheatsheet (4)

Features within the Visual Editor

  • Insert citations
  • Style options
  • Add/edit attributes
  • Switch to source editor

Rendered Output

rmarkdown :: Cheatsheet (5)

Features within the Rendered Output Window

  • File path to output document
  • Find in document
  • Publish to rpubs.com, shinyapps.io, Posit Connect
  • Reload document

Embed Code With knitr

Code Chunks

Surround code chunks with ```{r} and ``` or use the Insert Code Chunk button. Add a chunk label and/or chunk options inside the curly braces after r.

```{r chunk-label, include = FALSE}```

Set Global Options

Set options for the entire document in the first chunk.

```{r include = FALSE}knitr::opts_chunk$set(message = FALSE)```

Inline Code

Insert `r <code>` into text sections. Code is evaluated at render and results appear as text.

The markdown text

Built with `r getRversion()` 

will render as “Built with 4.4.0” in the output file.

Chunk Options

Table of chunk options. The first column is the option name, the second column is the option’s default value, the third column describes what the option does.
OptionDefaultEffects
echoTRUEdisplay code in output document
errorFALSETRUE (display error messages in doc), FALSE (stop render when error occurs)
evalTRUErun code in chunk
includeTRUEinclude chunk in doc after running
messageTRUEdisplay code messages in document
warningTRUEdisplay code warnings in document
results"markup""asis" (pass through results), "hide" (don’t display results), "hold" (put all results below all code)
fig.align"default""left", "right", or "center"
fig.altNULLalt text for a figure
fig.capNULLfigure caption as a character string
fig.path"figure/"prefix for generating file paths
fig.width & fig.height7plot dimensions in inches
out.widthrescales output width, e.g."75%", "300px"
collapseFALSEcollapse all sources & output into a single block
comment"##"prefix for each line of results
childNULLfile(s) to knit and then include
purlTRUEinclude or exclude a code chunk when extracting source code with knitr::purl()

See more options and defaults by running str(knitr::opts_chunk$get()).

Insert Citations

Create citations from a bibliography file, a Zotero library, or from DOI references.

Build Your Bibliography

  • Add BibTex or CSL bibliographies to the YAML header.

    ---title: "My Document"bibliography: references.biblink-citations: TRUE---
  • If Zotero is installed locally, your main library will automatically be available.

  • Add citations by DOI by searching “from DOI” in the Insert Citation dialog.

Insert Citations

  • Access the Insert Citations dialog in the Visual Editor by clicking the @ symbol in the toolbar or by clicking Insert > Citation.
  • Add citations with markdown syntax by typing [@cite] or @cite.

Insert Tables

Output data frames as tables using kable(data, caption).

```{r}data <- faithful[1:4,]knitr::kable(data, caption = "Tables with kable")```

Other table packages include flextable, gt, and kableExtra.

Write With Markdown

The syntax on the left renders as the output on the right.

Table of markdown syntax and rendered examples. The syntax in the first column renders to the output in the second column.
Plain text.

Plain text.

End a line with two spaces tostart a new paragraph.

End a line with two spaces to

start a new paragraph.

Also end a line with a backslash\to make a new line.

Also end a line with a backslash

to make a new line.

*italics* and **bold**
italics and bold
superscript^2^/subscript~2~
superscript2 /subscript2
~~strike through~~
strike through
escaped: \* \_ \\
escaped: * _ \
en dash: --, em dash: ---
en dash: –, em dash: —
# Header 1
## Header 2

Header 2

...
###### Header 6
Header 6
- unordered list- item 2 - item 2a (indent 1 tab) - item 2b
  • unordered list

  • item 2

    • item 2a (indent 1 tab)

    • item 2b

1. ordered list2. item 2 - item 2a (indent 1 tab) - item 2b
  1. ordered list

  2. item 2

    • item 2a

    • item 2b

<link url>
https://posit.co/
[This is a link.](link url)
This is a link.
[This is another link.][id].At the end of the document:[id]: link url
This is another link.
![Caption](image.png)or![Caption](id2)At the end of the document include:[id2]: image.png

rmarkdown :: Cheatsheet (6)

`verbatim code`
verbatim code
```multiple linesof verbatim code```
multiple linesof verbatim code
> block quotes

block quotes

equation: $e^{i \pi} + 1 = 0$
equation: \(e^{i \pi} + 1 = 0\)
equation block:$$E = mc^{2}$$

equation block:

\[E = mc^{2}\]

horizontal rule:---

horizontal rule:

|Right|Left|Default|Center||----:|:---|-------|:----:||12 |12 |12 |12 ||123 |123 |123 |123 ||1 |1 |1 |1 |Table: Caption text, example rendered table
Caption text, example rendered table.
RightLeftDefaultCenter
12121212
123123123123
1111

HTML Tabsets

## Results {.tabset}### Plotstext### Tablesmore text

Results

text

more text

Set Output Formats and Their Options in YAML

Use the document’s YAML header to set an output format and customize it with output options. Indent format 2 characters, indent options 4 characters.

---title: "My Document"author: "Author Name"output: html_document:  toc: true toc-location: left---

Output Format Table

Table of output formats. The output format in the first column creates the file type in the second column.
Output FormatCreates
html_document.html
pdf_document1.pdf
word_documentMicrosoft Word (.docx)
powerpoint_presentationMicrosoft PowerPoint (.pptx)
odt_documentOpenDocument Text
rtf_documentRich Text Format
md_documentMarkdown
github_documentMarkdown for Github
ioslides_presentationsioslides HTML slides
slidy_presentationSlidy HTML slides
beamer_presentation2Beamer slides

Also see flexdashboard, bookdown, distill, and blogdown.

Output Options Table

Table of output options. The first column is the option name, the second column is the description and possible values, and then remaining columns show what file types each option can be applied to.
Important OptionsDescriptionHTMLPDFMS WordMS PPT
anchor_sectionsShow section anchors on mouse hover (TRUE or FALSE)X
citation_packageThe LaTeX package to process citations (“default”, “natbib”, biblatex”)
code_downloadGive readers an option to download the .Rmd source code (TRUE or FALSE)X
code_foldingLet readers toggle the display of R code (“none”, “hide”, or “show”)X
cssCSS or SCSS file to use to style the document (e.g.“style.css”)X
devGraphics device to use for figure output (e.g.“png”, “pdf”)XX
df_printMethod for printing data frames (“default”, “kable”, “tibble”, “paged”)XXXX
fig_captionShould figures be rendered with captions (TRUE or FALSE)XXXX
highlightSyntax highlighting (“tango”, “pygments”, “kate”, “zenburn”, “textmate”)XXX
includesFile of content to place in doc (“in_header”, “before_body”, “after_body”)XX
keep_mdKeep the Markdown .md file generated by knitting (TRUE or FALSE)XXXX
keep_texKeep the intermediate TEX file used to convert to PDF (TRUE or FALSE)X
latex_engineLaTeX engine for producing PDF output (“pdflatex”, “xelatex”, or “lualatex”)X
reference_docx/_docdocx/pptx file containing styles to copy in the output (e.g.“file.docx”, “file.pptx”)XX
themeTheme options (see Bootswatch and Custom Themes below)X
tocAdd a table of contents at start of document (TRUE or FALSE)XXXX
toc_depthThe lowest level of headings to add to table of contents (e.g.2, 3)XXXX
toc_floatFloat the table of contents to the left of the main document content (TRUE or FALSE)X

Use ?<output_format> to see all of a format’s options, e.g.?html_document

More Header Options

Parameters

Parameterize your documents to ruse with new inputs (e.g.data, values, etc.).

  1. Add parameters in the header as sub-values of params.

    ---params: state: "hawaii"---
  2. Call parameters in code using params$name.

    ```{r}data <- df[,params$state]summary(data)```
  3. Set parameters with Knit with Parameters or the params argument of render().

Reusable Templates

  1. Create a new package with an inst/rmarkdown/templates directory.

  2. Add a folder containing template.yaml (below) and skeleton.Rmd (template contents).

    ---name: "My Template"---
  3. Install the package to access template by going to File > New R Markdown > From Template.

Bootswatch Themes

Customize HTML documents with Bootswatch themes from the bslib package using the theme output option. Use bslib::bootswatch_themes() to list available themes.

---title: "My Document"author: "Author Name"output: html_document: theme: bootswatch: solar---

Custom Themes

Customize individual HTML elements using bslib variables. Use ?bs_theme to see more variables.

---output: html_document: theme: bg: "#121212" fg: "#E4E4E4" base_font: google: "Prompt"---

More on bslib at https://pkgs.rstudio.com/bslib/.

Styling With CSS and SCSS

Add CSS and SCSS to your documents by adding a path to a file with the css option in the YAML header.

---title: "My Document"author: "Author Name"output: html_document: css: "style.css"---

Apply CSS styling by writing HTML tags directly or:

  • Use markdown to apply style attributes inline.

    • Bracketed Span
      A [green]{.my-color} word. will render as “A green word.”

    • Fenced Div

      :::{.my-color}All of these wordsare green:::

      will render as

      All of these words

      are green.

  • Use the Visual Editor. Go to Format > Div/Span and add CSS styling directly with Edit Attributes.

Interactivity

Turn your report into an interactive Shiny document in 4 steps:

  1. Add runtime: shiny to the YAML header.

    ---output: html_documentruntime: shiny---
  2. Call Shiny input functions to embed input objects.

  3. Call Shiny output functions to embed reactive output.

    ```{r echo = FALSE}numericInput("n", "How many cars?", 5)renderTable({ head(cars, input$n)})```
  4. Render with rmarkdown::run() or click Run Document in RStudio IDE.

Also see Shiny Prerendered for better performance. https://rmarkdown.rstudio.com/authoring_shiny_prerendered.

Embed a complete Shiny app into your document with shiny::shinyAppDir(). More at https://bookdown.org/yihui/rmarkdown/shiny-embedded.html.

Render

When you render a document, rmarkdown:

  1. Runs the code and embeds results and text into an .md file with knitr.
  2. Converts the .md file into the output format with Pandoc.

Save, then Knit to preview the document output. The resulting HTML/PDF/MS Word/etc. document will be created and saved in the same directory as the .Rmd file.

Use rmarkdown::render() to render/knit in the R console. See ?render for available options.

Footnotes

  1. PDFs and Beamer slides require LaTeX, use tinytex::install_tinytex().↩︎

  2. PDFs and Beamer slides require LaTeX, use tinytex::install_tinytex().↩︎

rmarkdown :: Cheatsheet (2024)

FAQs

What does the --- delimiter indicate in an R markdown notebook? ›

Rmd extension. The first four lines are a metadata header that indicate the title (printed at the top of your report) and the output format. The "---" delimiters indicate the start and end of the header, so you should leave them alone.

How to separate paragraphs in RMarkdown? ›

In order to start a new paragraph, you need to add white space between the two paragraphs: Here is an example of text with a line break and white space. You may expect this line to appear in a new paragraph and it does.

What does echo false do in r? ›

echo = FALSE prevents code, but not the results from appearing in the finished file. This is a useful way to embed figures.

What does eval false do? ›

"eval = FALSE" ` will present your code without the associated output. For example: how to calculate two plus two… "echo = FALSE" will not present your code but will show the associated output.

What does the --- delimiter three hyphens indicate in an R Markdown notebook? ›

This header is established by a set of three dashes --- as delimiters (one starting set, and one ending set). This part of the file requires you to use YAML syntax (Yet Another Markup Language.) Within the delimiter sets of dashes, you specify settings (or metadata) that will apply to the entire document.

What delimiter should they type in their .RMD file? ›

The correct delimiter for marking the beginning of a code chunk in an R Markdown (. Rmd) file is ```{R }. This combination is essential for running R code within R Markdown documents, where backticks and braces are used to define code chunks, and the # symbol is used for comments in scripts.

What does this mean knitr :: opts_chunk set echo true? ›

```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` is used to specify any global settings to be applied to the R Markdown script. The example sets all code chunks as “echo=TRUE”, meaning they will be included in the final rendered version.

What does unnamed chunk mean in R? ›

Chunk labels are mainly used in filenames of plots and cache. If the label of a chunk is missing, a default one of the form unnamed-chunk-i will be generated, where i is incremental.

How to silence warnings in R Markdown? ›

We discussed three methods to remove warning messages in R Markdown documents: using suppressWarnings() function, setting the warnings option to FALSE in YAML metadata, and using the knitr::opts_chunk$set() function to set global options for all code chunks in the document.

Why eval is not recommended? ›

Malicious code : invoking eval can crash a computer. For example: if you use eval server-side and a mischievous user decides to use an infinite loop as their username. Terribly slow : the JavaScript language is designed to use the full gamut of JavaScript types (numbers, functions, objects, etc)… Not just strings!

How to hide code chunk in R Markdown? ›

To hide a specific code chunk set echo to “false” ( echo=false ). Include the code chunk in the rendered document with echo=true . Exclude the code chunk in the rendered document with echo=false .

What does "knit" mean in R? ›

There are two ways to render an R Markdown document into its final output format. If you are using RStudio, then the “Knit” button (Ctrl+Shift+K) will render the document and display a preview of it.

What does the r delimiter indicate? ›

Explanation: The "r delimiter (three backticks followed by an r contained inside curly brackets) in an R Markdown notebook indicates the start of a code chunk. This syntax is used to delineate where executable R code begins within the notebook.

What is a delimiter in a data file? ›

Delimiters in the Data File. Delimiters are those characters in the data file that separate fields and mark the end of records.

What does the --- delimiter three hyphens indicate in an R Markdown notebook 1 point code chunk YAML metadata bold text italic text? ›

A YAML header (optional) at the top of the document:

The header is enclosed by two sets of three dashes --- . This block allows you to fine-tune the output of your document. It's a set of key:value pairs that describes the file that should be built from the R Markdown file.

What are the different types of delimiters in r? ›

Any character can be used as a delimiter; however, the comma, tab, and colon are the most widely used, and such data files can be read in R as follows.

Top Articles
Latest Posts
Article information

Author: Kelle Weber

Last Updated:

Views: 6448

Rating: 4.2 / 5 (73 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Kelle Weber

Birthday: 2000-08-05

Address: 6796 Juan Square, Markfort, MN 58988

Phone: +8215934114615

Job: Hospitality Director

Hobby: tabletop games, Foreign language learning, Leather crafting, Horseback riding, Swimming, Knapping, Handball

Introduction: My name is Kelle Weber, I am a magnificent, enchanting, fair, joyous, light, determined, joyous person who loves writing and wants to share my knowledge and understanding with you.