markdown
r-markdown
cheat-sheet
data-science
statistics

R Markdown Cheat Sheet: Syntax, Chunks, and Output

April 9, 2026 · 9 min read

R Markdown Cheat Sheet: Syntax, Chunks, and Output

An r markdown cheat sheet gives you quick access to YAML headers, code chunk options, inline R expressions, and output format settings. R Markdown documents combine prose, code, and results in a single reproducible file. Over 4.2 million R Markdown files exist on GitHub as of 2024, making it one of the most popular formats for statistical reporting and academic publishing.

What Does This R Markdown Cheat Sheet Cover?

This r markdown cheat sheet starts with the fundamentals. R Markdown (.Rmd) is an authoring format that lets you embed R code directly into markdown documents. When you "knit" an .Rmd file, the knitr package runs your code, captures the output, and weaves it together with your narrative text. The final result can be HTML, PDF, Word, or even a slideshow.

Think of it as a lab notebook that actually runs your experiments. You write your analysis once, and anyone can reproduce it by knitting the same file. According to RStudio's documentation, R Markdown supports over 40 output formats through various packages.

If you need a general markdown reference, our markdown editor is a great place to practice basic syntax before adding R-specific features.

How Do You Set Up a YAML Header?

Every R Markdown document starts with a YAML header enclosed in triple dashes. This header controls the document's title, author, date, and output format:

---
title: "Quarterly Sales Report"
author: "Data Team"
date: "2025-01-15"
output:
  html_document:
    toc: true
    toc_float: true
    theme: flatly
    code_folding: hide
---

The output field is the most important part. Here are common output configurations:

Output FormatYAML ValuePackage Required
HTML pagehtml_documentrmarkdown
PDF documentpdf_documentrmarkdown + tinytex
Word documentword_documentrmarkdown
Slides (HTML)ioslides_presentationrmarkdown
Slides (Beamer)beamer_presentationrmarkdown + tinytex
Dashboardflexdashboard::flex_dashboardflexdashboard
Bookbookdown::gitbookbookdown

You can specify multiple output formats in one YAML header and render whichever you need. About 67% of R Markdown users primarily output to HTML, with PDF as the second most common choice.

How Do knitr Code Chunks Work?

Code chunks are the heart of this r markdown cheat sheet. They're blocks of R code that get executed when you knit the document. A basic chunk looks like this:

```{r chunk-name, echo=TRUE, message=FALSE}
library(ggplot2)
ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point()
```

The chunk header inside {r } accepts dozens of options. Here are the ones you'll use most:

Essential Chunk Options

OptionDefaultPurpose
echoTRUEShow source code in output
evalTRUEActually run the code
includeTRUEInclude chunk output in document
messageTRUEDisplay R messages
warningTRUEDisplay warnings
fig.width7Figure width in inches
fig.height5Figure height in inches
fig.capNULLFigure caption text
cacheFALSECache results for faster re-knitting
results'markup'How to display text results

Setting Global Chunk Options

Instead of repeating options in every chunk, set defaults at the top of your document:

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  echo = TRUE,
  message = FALSE,
  warning = FALSE,
  fig.width = 8,
  fig.height = 5
)
```

This saves a lot of typing. I'd say about 90% of R Markdown documents I've reviewed include a setup chunk like this. It's considered best practice for a good reason.

How Do You Use Inline R Code?

Inline R code lets you embed computed values directly in your prose. Use single backticks with the letter r:

The dataset contains `r nrow(mtcars)` observations and `r ncol(mtcars)` variables.

This renders as: "The dataset contains 32 observations and 11 variables."

Inline code is perfect for dynamic reporting. When your data changes, the numbers in your text update automatically. No more copy-pasting values from console output. According to a 2023 survey by the R Consortium, 58% of R users who write reports use inline code expressions.

What R Markdown Syntax Differs from Standard Markdown?

R Markdown uses Pandoc's extended markdown, which adds several features beyond basic markdown. Here's what you get on top of standard formatting:

Citations and Bibliography

Add a bibliography file to your YAML header:

---
bibliography: references.bib
csl: apa.csl
---

Then cite sources inline with [@author2024] for parenthetical citations or @author2024 for narrative citations. Pandoc auto-generates your reference list at the end.

Cross-References

With the bookdown package, you can cross-reference figures, tables, and sections:

See Figure \@ref(fig:scatter-plot) for the results.
Table \@ref(tab:summary-stats) shows descriptive statistics.

This is especially useful for longer documents and academic papers where you're referencing numbered elements throughout.

Math Equations

R Markdown supports LaTeX math just like Jupyter. Use $...$ for inline and $$...$$ for display equations. If you're working with both platforms, our Markdown to PDF converter handles LaTeX rendering well.

Tables from R Output

Generate formatted tables from R data frames using knitr's kable() function:

```{r}
knitr::kable(head(iris, 5), caption = "First five rows of iris dataset")
```

For fancier tables, the kableExtra, gt, and DT packages offer more control. The gt package alone has over 1.2 million monthly downloads on CRAN.

How Do You Control PDF Output?

PDF output requires a LaTeX installation. The easiest path is TinyTeX:

tinytex::install_tinytex()

Common PDF-specific YAML options:

output:
  pdf_document:
    latex_engine: xelatex
    toc: true
    number_sections: true
    fig_caption: true
    keep_tex: false

You can include raw LaTeX commands in your .Rmd file for fine-grained PDF control. Custom headers, footers, and page layouts are all possible through the includes option or a custom LaTeX template.

Converting your final markdown to other formats? Our Markdown to HTML tool handles the HTML side, while the PDF converter works well for non-R markdown files.

How Do You Create Parameterized Reports?

Parameterized reports let you reuse one template with different inputs. Add parameters to your YAML:

---
title: "Sales Report"
params:
  region: "North"
  quarter: 1
  year: 2025
---

Then reference them in code chunks as params$region, params$quarter, etc. Render with different values from R:

rmarkdown::render("report.Rmd", params = list(region = "South", quarter = 2))

This pattern is incredibly useful for generating monthly or regional reports automatically. Some organizations produce hundreds of parameterized reports from a single template.

What Are Common R Markdown Troubleshooting Tips?

No r markdown cheat sheet is complete without troubleshooting tips. Here are issues I see frequently and their fixes:

  • Knitting fails with package errors: Add library() calls in your setup chunk, not just in your interactive session.
  • Figures look tiny in PDF: Set fig.width and fig.height in chunk options or globally via opts_chunk$set().
  • Encoding problems: Save your .Rmd file as UTF-8 and add encoding: UTF-8 to your YAML if needed.
  • Slow knitting: Use cache = TRUE for expensive computations, but be aware that cached chunks won't re-run unless their code changes.

For formatting issues with your markdown syntax specifically, the markdown formatter can help identify structural problems.

Frequently Asked Questions

What's the difference between R Markdown and Quarto?

Quarto is the next-generation version of R Markdown, built by Posit (formerly RStudio). It supports R, Python, Julia, and Observable JS. R Markdown still works perfectly and has a larger ecosystem of existing packages.

Can you use Python in R Markdown?

Yes. The reticulate package lets you run Python chunks in R Markdown documents. Use {python} instead of {r} in your chunk headers.

How do you add a table of contents?

Set toc: true under your output format in the YAML header. For HTML, add toc_float: true for a sticky sidebar TOC.

What's the best way to share R Markdown reports?

Knit to HTML for web sharing, PDF for formal distribution, or use RPubs for free online publishing. You can also deploy to RStudio Connect or Posit Connect for enterprise sharing.

How do you include images from files?

Use standard markdown syntax: ![caption](path/to/image.png). For more control, use knitr::include_graphics("image.png") inside a code chunk with fig.cap set.

Can R Markdown produce interactive content?

Yes. HTML output supports interactive widgets through packages like plotly, leaflet, DT, and htmlwidgets. These don't work in PDF output.

How do you number equations in R Markdown?

Use the bookdown output formats (like bookdown::html_document2) and label equations with (\#eq:label). Reference them with \@ref(eq:label).

What YAML options control code appearance?

Use highlight (pygments, tango, espresso, etc.), code_folding (hide, show), and chunk options like echo, eval, and class.source for CSS styling.

Quick Reference Summary

This r markdown cheat sheet covered the essentials you need for daily work: YAML configuration, knitr chunk options, inline R code, output formats, citations, cross-references, and parameterized reports. Keep this r markdown cheat sheet handy as you build reproducible analyses and reports. For practicing general markdown before adding R-specific features, our online editor provides instant preview of your formatting.