R Markdown & Quarto
An analysis is only useful when other people can read it. Copying numbers and charts from the console into a Word file by hand is slow, and the report goes out of date as soon as the data changes. R Markdown and its successor Quarto solve this: you write text and R code in one file, and one command runs the code and builds a finished report in HTML, Word or PDF, with every number and chart produced fresh from the data.
In this lesson you will learn the structure of these documents, how chunks and inline code work, how to render them, and how the older R Markdown and the newer Quarto relate.
One file, three ingredients
Both formats mix three things in a plain text file:
- A YAML header at the top, between two lines of
---, with the title, author and output format. - Markdown text: headings with
#, bold with**, lists with-, links and so on. - Code chunks: blocks of R code that run when the document is rendered. Their output (tables, numbers, charts) is placed in the report right after the code.
Here is a small Quarto report, saved as air-report.qmd:
---
title: "Air quality in New York, summer 1973"
author: "Ananya Sharma"
format: html
---
## Temperature
The data has 153 days of readings.
````{r}
#| label: temp-summary
#| echo: false
summary(airquality$Temp)
````
The average temperature was `r round(mean(airquality$Temp), 1)` degrees F.
````{r}
#| label: fig-temp
#| fig-cap: "Daily temperature by month"
boxplot(Temp ~ Month, data = airquality)
````A code chunk starts with a line of backticks followed by {r} and ends with a line of the same backticks. Most files use three backticks; knitr and Quarto also accept four, as shown here. The part of the sentence written as a backtick, r round(mean(airquality$Temp), 1) and a closing backtick is inline code: when the report is rendered, it is replaced by the number itself, 77.9. If the data changes, the sentence updates itself.
Chunk options
Chunk options control what appears in the report. In Quarto you write them at the top of the chunk as special comments starting with #|, in YAML style:
| Option | Effect |
|---|---|
echo: false | Hide the code, show only its output |
eval: false | Show the code but do not run it |
include: false | Run the code but show nothing (useful for loading data) |
warning: false, message: false | Hide warnings or messages |
fig-cap: "..." | Caption for a chart |
fig-width: 6, fig-height: 4 | Chart size in inches |
label: fig-temp | A name for the chunk; a fig- label lets you cross-reference the chart |
Options for the whole document go in the YAML header under execute:, for example echo: false to hide all code in a report for managers.
The R code inside a chunk is ordinary R. You can try it here before putting it in a report:
summary(airquality$Temp)
round(mean(airquality$Temp), 1)
hot_days <- sum(airquality$Temp >= 90)
sprintf("There were %d days at or above 90 F.", hot_days)Min. 1st Qu. Median Mean 3rd Qu. Max. 56.00 72.00 79.00 77.88 85.00 97.00 [1] 77.9 [1] "There were 17 days at or above 90 F."
In a report, the last line would be inline code inside a sentence instead of a sprintf() call.
Rendering a document
Rendering runs every chunk from top to bottom in a fresh R session and builds the output file.
- In RStudio, open the file and click Render (for
.qmd) or Knit (for.Rmd). - In Positron, use the Quarto: Preview command or the preview button.
- From a terminal, with the Quarto command-line tool installed:
quarto render air-report.qmd
quarto render air-report.qmd --to docx
quarto preview air-report.qmdquarto render writes the output file (here air-report.html); --to docx makes a Word file and --to pdf a PDF. quarto preview opens the report in a browser and re-renders it every time you save. From the R console you can use the quarto R package: quarto::quarto_render("air-report.qmd").
PDF output needs a LaTeX installation; quarto install tinytex installs a small one. HTML needs nothing extra and is the best format to start with.
R Markdown: the older format
R Markdown (.Rmd files, the rmarkdown package) came first, and you will meet many existing .Rmd reports, courses and books. The structure is almost the same:
---
title: "Air quality report"
output: html_document
---
````{r, echo=FALSE}
summary(airquality$Temp)
````The differences you will notice:
R Markdown (.Rmd) | Quarto (.qmd) | |
|---|---|---|
| Output setting in YAML | output: html_document | format: html |
| Chunk options | Usually in the header: {r, echo=FALSE} | Usually #| comment lines: #| echo: false |
| Render | Knit button or rmarkdown::render("file.Rmd") | Render button or quarto render file.qmd |
| Languages | Mainly R | R, Python, Julia and Observable JS |
| Needs R | Yes | No (it is a separate command-line tool) |
Posit, which develops both, says R Markdown is not going away: it stays supported and maintained, but most new features go into Quarto. Quarto can render most .Rmd files without changes. For new work, choose Quarto; for an existing R Markdown project, there is no need to convert.
What you can build
The same source can become many kinds of output:
- Reports in HTML, Word or PDF, with tables of contents and numbered figures.
- Slides (
format: revealjsin Quarto). - Websites and books made of several pages (Quarto projects).
- Parameterised reports: one template rendered for each city, branch or month by changing a parameter.
Common mistakes
- Using objects created in the console. The report runs in a fresh session; load data inside the document.
- Forgetting the blank lines around chunks and headings, which can break the Markdown formatting.
- Calling
install.packages()inside a chunk. It reinstalls on every render; install once in the console. - Hard-coding numbers in sentences. Use inline code so text and data never disagree.
Key points
- R Markdown (
.Rmd) and Quarto (.qmd) combine a YAML header, Markdown text and R code chunks in one file. - Rendering runs the code in a fresh session and builds HTML, Word, PDF, slides or websites.
- Chunk options such as
echo: falseandfig-capcontrol what appears; Quarto writes them as#|comments. - Inline code puts computed numbers into sentences, so the report updates with the data.
- Quarto is the newer, multi-language system; R Markdown remains supported for existing work.
Exercise
Write the source of a short Quarto document for a weekly sales report of a shop in Pune. It should have a title, your name, HTML format, a hidden chunk that creates a vector of seven daily sales figures, a sentence with the total sales as inline code, and a chunk that draws a bar chart with a caption. Check the R code in the browser first.
Show solution
---
title: "Weekly sales, Pune shop"
author: "Rohan Patil"
format: html
---
````{r}
#| include: false
sales <- c(Mon = 4200, Tue = 3900, Wed = 4600, Thu = 5100,
Fri = 6800, Sat = 9200, Sun = 8700)
````
Total sales this week were Rs `r format(sum(sales), big.mark = ",")`.
````{r}
#| label: fig-sales
#| fig-cap: "Daily sales"
#| echo: false
barplot(sales, col = "darkorange", ylab = "Sales (Rs)")
````sales <- c(Mon = 4200, Tue = 3900, Wed = 4600, Thu = 5100,
Fri = 6800, Sat = 9200, Sun = 8700)
format(sum(sales), big.mark = ",")
barplot(sales, col = "darkorange", ylab = "Sales (Rs)")[1] "42,500"
include: false runs the first chunk without showing it, so the report starts with clean text. The inline code becomes "42,500" when rendered, and echo: false shows the chart without its code.
Quick Quiz
1. What is the file extension of a Quarto document?
Quarto documents end in .qmd; R Markdown documents end in .Rmd.
2. Which chunk option hides the code but shows its output?
echo: false hides the source code; the results still appear.
3. Why can a report fail to find a variable that exists in your console?
The document must create or load everything it uses.
4. Which command builds a Word version of report.qmd?
--to docx selects the Word format.
Learn R Programming with a mentor
Free lessons get you started. Our Data Science & Machine Learning training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
