R Markdown
last modified November 19, 2026
R Markdown mixes prose, R code, and the output of that code in one source file.
The file uses Markdown for the text and fenced chunks for the code; the
knitr package runs the chunks and replaces them with their results, and
pandoc converts the combined document to HTML, PDF, Word, or Markdown.
The rmarkdown package ties both steps together behind
render. This article covers the YAML header, code chunks and inline
code, chunk options, tables and figures, document layout, alternative output
formats, and a complete report. The examples use R 4.5.2 with rmarkdown 2.32,
knitr 1.52, and pandoc 3.10. Each script writes a source document, renders it,
and then reads the HTML back with xml2 to check a few facts about the result.
The examples need the rmarkdown and xml2 packages, which are not part of base
R. Install them once with
install.packages(c("rmarkdown", "xml2")); the
installing packages section of the
introduction explains the details. Rendering also needs pandoc, which RStudio
bundles; outside RStudio, install it from
pandoc.org.
A first document
An R Markdown file starts with a YAML header between two lines of three
hyphens. The header sets the title and the output format, here
html_document. Below it, ordinary Markdown headings and paragraphs
mix with chunks that open with three backticks, the letter r in
braces, and close with three backticks. render executes the chunks,
converts the document, and writes the output file next to the source.
lines <- c(
"---",
"title: \"Sales report\"",
"output: html_document",
"---",
"## Summary",
"The report was generated from R Markdown.",
"```{r}",
"total <- sum(c(12, 18, 30))",
"total",
"```"
)
writeLines(lines, "report.Rmd")
rmarkdown::render("report.Rmd", quiet = TRUE)
page <- xml2::read_html("report.html")
cat("title:", xml2::xml_text(xml2::xml_find_first(page, "//title")), "\n")
text <- xml2::xml_text(page)
cat("total shown:", grepl("## [1] 60", text, fixed = TRUE), "\n")
unlink(c("report.Rmd", "report.html"))
The script writes report.Rmd, renders it quietly, and reads the
title back from the HTML head. The title is the one from the YAML header. The chunk assigned sixty to total and printed
it, so the page also contains the value below the code; the last check confirms
that the output appears as ## [1] 60. The source file is
deleted at the end of the script to keep the working directory clean.
$ Rscript first.R title: Sales report total shown: TRUE
Code chunks and inline code
A chunk can hold several statements, and only the last visible value is
printed, as at the console. Objects created in one chunk remain available in
the chunks that follow, because knitr evaluates them in one R session. Inline
code uses a single pair of backticks with an r inside and inserts
a value into a sentence, which is how a report quotes a number computed
earlier.
library(rmarkdown)
lines <- c(
"---",
"title: \"Chunk output\"",
"output: html_document",
"---",
"",
"## Totals",
"",
"```{r}",
"orders <- data.frame(qty = c(2, 5, 3), price = c(10, 4, 12))",
"total <- sum(orders$qty * orders$price)",
"total",
"```",
"",
"The order total is `r total` euros.",
"",
"```{r}",
"paste(\"rows:\", nrow(orders))",
"```"
)
writeLines(lines, "chunks.Rmd")
render("chunks.Rmd", quiet = TRUE)
page <- xml2::read_html("chunks.html")
paras <- xml2::xml_text(xml2::xml_find_all(page, "//p"))
cat("paragraphs:", length(paras), "\n")
cat("last:", paras[length(paras)], "\n")
pres <- xml2::xml_text(xml2::xml_find_all(page, "//pre"))
cat("chunk 1:", pres[2], "\n")
cat("chunk 2:", pres[4], "\n")
unlink(c("chunks.Rmd", "chunks.html"))
The first chunk prints 76, the order total. The sentence after it renders as
"The order total is 76 euros.", because the inline expression sees the same
total object. The second chunk prints the number of rows. The
script reads the rendered page and shows the inline sentence plus the two
chunk outputs, each prefixed with ##, which is knitr's marker for
console output.
$ Rscript chunks.R paragraphs: 1 last: The order total is 76 euros. chunk 1: ## [1] 76 chunk 2: ## [1] "rows: 3"
Chunk options
The text after the chunk label holds options that control the chunk.
echo = FALSE runs the code but hides it, eval = FALSE
shows the code but does not run it, results = "hide" keeps the
output out of the document, message = FALSE suppresses messages,
and warning = FALSE would suppress warnings. The options can be
combined, and they are written inside the braces after a comma.
library(rmarkdown)
lines <- c(
"---",
"title: \"Chunk options\"",
"output: html_document",
"---",
"",
"## Hidden and skipped code",
"",
"```{r, echo=FALSE}",
"hidden <- 99",
"```",
"",
"```{r, eval=FALSE}",
"skipped <- read.csv(\"missing.csv\")",
"```",
"",
"```{r, results=\"hide\", echo=FALSE}",
"print(\"hidden output\")",
"```",
"",
"```{r, message=FALSE, echo=FALSE}",
"message(\"hidden note\")",
"```",
"",
"```{r}",
"as.numeric(\"abc\")",
"```"
)
writeLines(lines, "options.Rmd")
render("options.Rmd", quiet = TRUE)
text <- xml2::xml_text(xml2::read_html("options.html"))
cat("hidden code:", grepl("hidden <- 99", text, fixed = TRUE), "\n")
cat("skipped code:", grepl("skipped <- read.csv", text, fixed = TRUE), "\n")
cat("hidden output:", grepl("hidden output", text, fixed = TRUE), "\n")
cat("hidden note:", grepl("hidden note", text, fixed = TRUE), "\n")
cat("warning:", grepl("NAs introduced by coercion", text, fixed = TRUE), "\n")
unlink(c("options.Rmd", "options.html"))
The hidden assignment leaves no trace in the page, and the skipped chunk keeps
its code but never runs. The hidden output and the hidden message are absent
as well. The last chunk calls as.numeric on a word, and the
coercion warning appears in the document, because warnings are shown by
default. The five checks read the rendered text and report which expectations
hold.
$ Rscript chunk-options.R hidden code: FALSE skipped code: TRUE hidden output: FALSE hidden note: FALSE warning: TRUE
Tables and figures
knitr::kable turns a data frame into an HTML table with the column
names in a header row. A chunk that draws a plot saves the figure and inserts
it at the same position in the document. The options fig.width and
fig.height set the size in inches, and the default HTML output
embeds the image in the file, so the result is a single portable page.
library(rmarkdown)
lines <- c(
"---",
"title: \"Tables and figures\"",
"output: html_document",
"---",
"",
"## Top speeds",
"",
"```{r}",
"knitr::kable(head(cars, 3))",
"```",
"",
"## Stopping distance",
"",
"```{r, fig.width=6, fig.height=4}",
"plot(cars, main = \"Stopping distance\")",
"```"
)
writeLines(lines, "figures.Rmd")
render("figures.Rmd", quiet = TRUE)
page <- xml2::read_html("figures.html")
cat("tables:", length(xml2::xml_find_all(page, "//table")), "\n")
cat("table rows:", length(xml2::xml_find_all(page, "//table//tr")), "\n")
cat("images:", length(xml2::xml_find_all(page, "//img")), "\n")
unlink(c("figures.Rmd", "figures.html"))
The rendered page has one table with four rows: a header and the three cars
from head(cars, 3). It also has one image, the scatter plot of
stopping distance. The figure is stored inside the HTML file as a data URI,
which is why no separate figure directory appears next to the document. A
PDF output would embed the image differently but keep the same source.
$ Rscript figures.R tables: 1 table rows: 4 images: 1
Document layout
The output format accepts options of its own, written as a nested YAML block.
toc: true adds a table of contents built from the headings,
number_sections: true numbers them, and theme selects
a Bootstrap style for the HTML page. These options change the template, not
the R code, so the same chunks can be reused with a different look.
library(rmarkdown)
lines <- c(
"---",
"title: \"Yearly review\"",
"output:",
" html_document:",
" toc: true",
" number_sections: true",
" theme: united",
"---",
"",
"# Results",
"",
"The first section.",
"",
"# Method",
"",
"The second section."
)
writeLines(lines, "layout.Rmd")
render("layout.Rmd", quiet = TRUE)
page <- xml2::read_html("layout.html")
cat("toc:", length(xml2::xml_find_all(page, "//div[@id='TOC']")), "\n")
numbers <- xml2::xml_text(xml2::xml_find_all(page, "//span[@class='header-section-number']"))
cat("numbers:", numbers, "\n")
cat("sections:", length(xml2::xml_find_all(page, "//div[contains(@class, 'section level1')]")), "\n")
unlink(c("layout.Rmd", "layout.html"))
The page contains one element with the identifier TOC, the two
top-level sections are numbered 1 and 2, and both carry the
section level1 class. The numbering appears in the heading text
and in the table of contents. A deeper document would add level-two headings,
which the same options number as 1.1, 1.2, and so on.
$ Rscript sections.R toc: 1 numbers: 1 2 sections: 2
Other output formats
The source is independent of the output format. Passing
output_format to render overrides the header for one
call, so the same file can produce a web page and a Markdown document without
being edited. md_document is useful for a README or for a document
that another system will convert further. PDF and Word outputs are also
available; PDF goes through LaTeX and needs a separate installation, while HTML
and Markdown need only pandoc.
library(rmarkdown)
lines <- c(
"---",
"title: \"Portable notes\"",
"output: html_document",
"---",
"",
"## Notes",
"",
"A short document in two formats.",
"",
"```{r}",
"2 + 2",
"```"
)
writeLines(lines, "formats.Rmd")
render("formats.Rmd", output_format = "html_document", quiet = TRUE)
cat("html:", file.exists("formats.html"), "\n")
render("formats.Rmd", output_format = "md_document", quiet = TRUE)
cat("md:", file.exists("formats.md"), "\n")
cat("lines:", length(readLines("formats.md")), "\n")
cat(readLines("formats.md"), sep = "\n")
unlink(c("formats.Rmd", "formats.html", "formats.md"))
Both files are created from one source. The HTML file carries the title from
the header, while the Markdown file starts at the section heading: the title is
metadata that the HTML template renders and the Markdown writer does not. The
code chunk becomes an indented block, and its output is indented below it with
the ## prefix. The seven lines match the visible structure of the
document.
$ Rscript formats.R
html: TRUE
md: TRUE
lines: 7
## Notes
A short document in two formats.
2 + 2
## [1] 4
A complete report
The final example builds a report from a saved data set. The R script writes the data to an RDS file, writes a document that reads it back, aggregates revenue by product, shows the result as a table, and adds a bar chart. The total revenue is computed inline, so the sentence and the table always agree.
library(rmarkdown)
sales <- data.frame(
product = c("pen", "book", "bag", "cup", "book", "pen"),
qty = c(10, 3, 2, 8, 6, 4),
price = c(2.5, 12, 30, 8, 12, 2.5)
)
lines <- c(
"---",
"title: \"Sales summary\"",
"output: html_document",
"---",
"",
"## By product",
"",
"```{r}",
"sales <- readRDS(\"sales.rds\")",
"by_product <- aggregate(qty * price ~ product, data = sales, FUN = sum)",
"names(by_product)[2] <- \"revenue\"",
"by_product <- by_product[order(-by_product$revenue), ]",
"knitr::kable(by_product, row.names = FALSE)",
"```",
"",
"Total revenue is `r sum(sales$qty * sales$price)` euros.",
"",
"```{r}",
"barplot(by_product$revenue, names.arg = by_product$product,",
" main = \"Revenue by product\", ylab = \"euros\")",
"```"
)
saveRDS(sales, "sales.rds")
writeLines(lines, "sales.Rmd")
render("sales.Rmd", quiet = TRUE)
page <- xml2::read_html("sales.html")
cat("tables:", length(xml2::xml_find_all(page, "//table")), "\n")
cat("table rows:", length(xml2::xml_find_all(page, "//table//tr")), "\n")
cat("images:", length(xml2::xml_find_all(page, "//img")), "\n")
line <- xml2::xml_find_first(page, "//p[contains(., 'Total revenue')]")
cat("summary:", xml2::xml_text(line), "\n")
unlink(c("sales.rds", "sales.Rmd", "sales.html"))
The page has one table with a header and four product rows, one image, and the sentence "Total revenue is 267 euros." The table sorts the products by revenue, and the bar chart uses the same order. The report reads its input from a file rather than from the document, which is the usual arrangement when the data changes and the report is regenerated on a schedule.
$ Rscript complete.R tables: 1 table rows: 5 images: 1 summary: Total revenue is 267 euros.
Next steps
The Quarto article covers the newer system that uses the same knitr engine and pandoc converter with a different command-line tool and a slightly different syntax for options. The data I/O article explains the RDS file used by the complete report, and the base graphics article covers the plotting calls that the chunks contain. The creating packages article shows how a package documents its functions with roxygen2, which is a different kind of generated document.
Source
R Markdown: dynamic documents for R
R Markdown: The Definitive Guide
knitr: elegant, flexible, and fast dynamic report generation
pandoc: a universal document converter
In this article we wrote R Markdown documents from R scripts and rendered them
with rmarkdown::render. We combined Markdown prose with code
chunks and inline values, controlled the chunks with echo, eval, results,
message, and warning options, and inserted a table and a figure. A table of
contents and numbered sections changed the layout, a second output format
reused the same source, and the final report aggregated a data file into a
table and a chart. The series continues with Quarto.
Author
List all R Language tutorials.