EthicsComputerCourses
Join training +91 90532 10052

R Markdown & Quarto

R Programming · Lesson 27 of 29 Advanced 7 min read Updated

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:

  1. A YAML header at the top, between two lines of ---, with the title, author and output format.
  2. Markdown text: headings with #, bold with **, lists with -, links and so on.
  3. 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:

Text
---
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:

OptionEffect
echo: falseHide the code, show only its output
eval: falseShow the code but do not run it
include: falseRun the code but show nothing (useful for loading data)
warning: false, message: falseHide warnings or messages
fig-cap: "..."Caption for a chart
fig-width: 6, fig-height: 4Chart size in inches
label: fig-tempA 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:

RTry it yourself
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)
Output
   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:
Terminal
quarto render air-report.qmd
quarto render air-report.qmd --to docx
quarto preview air-report.qmd

quarto 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:

Text
---
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 YAMLoutput: html_documentformat: html
Chunk optionsUsually in the header: {r, echo=FALSE}Usually #| comment lines: #| echo: false
RenderKnit button or rmarkdown::render("file.Rmd")Render button or quarto render file.qmd
LanguagesMainly RR, Python, Julia and Observable JS
Needs RYesNo (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: revealjs in 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: false and fig-cap control 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
Text
---
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)")
````
RTry it yourself
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)")
Output
[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?

2. Which chunk option hides the code but shows its output?

3. Why can a report fail to find a variable that exists in your console?

4. Which command builds a Word version of report.qmd?

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