11  Quarto

According to the Quarto Website, Quarto is an open-source scientific and technical publishing system. It comes bundled with recent versions of RStudio (2022.07 or later), so it’s already available on your machines.

Quarto is part of a broader ecosystem of tools that support reproducible research. Platforms like GitHub, Jupyter, Docker, ArXiv, and bioRxiv can facilitate reproducibility in various ways. In this module, we won’t explore the paradigm of reproducible research in detail. Instead, we’ll focus on how to use Quarto to make your analyses and reports more appealing, interactive, and efficient.

In this lesson, we’ll weave code and narrative into professionally rendered Quarto documents and use GitHub to safely store, share, and administer our results.

11.1 Set up your work environment

Before creating your first Quarto document, we need to set up your GitHub environment.

Originally designed for software development, GitHub is also a powerful tool for managing changes in documents and data projects. Its version control system helps track edits, collaborate with others, and maintain a clear history of your work.

Even if you’re working solo, GitHub offers valuable features like change tracking, documentation, and easy sharing.

To set up your personal GitHub environment, follow these steps:

  1. Review the Hello-World Section in GitHub’s Quickstart Documentation. Initially, reading it is sufficient—no need to complete the tutorial yet.
  2. Create a GitHub account.
  3. Download and install Git. Git is a distributed VCS (version control system) that stores your project history locally and remotely. GitHub is a web-based interface that works seamlessly with Git. For a quick intro to Git’s core concepts, watch this video.
  4. In RStudio (under Tools > Global Options > Git / SVN), check “enable version control” and set the path to git. On Windows: C:\Program Files\Git\bin\git.exe. On macOS/Linux, the path is usually set automatically (e.g., /usr/bin/git or /opt/homebrew/bin/git if installed via Homebrew). After setting the path, restart RStudio.
  5. Create a repository on GitHub. You can skip the “Commit your first changes” section for now.
  6. By default, your repository will have one branch named main. Create an additional branch called dev off the main. Follow the instructions in the Hello-World Tutorial for guidance.
Note

For technical issues, please consult the discussion forum.

11.1.1 Tell Git who you are (one-time setup)

Before making your first commit, configure Git with your name and email. These values are stored locally and will be attached to each commit you make.

In the Terminal tab of RStudio, run:

git config --global user.name "Jane Doe"
git config --global user.email "jane.doe@example.com"

To verify:

git config --global --list

This setup is independent of how you authenticate with GitHub (via token or SSH key).

11.1.2 Authenticating with GitHub

Since 2021, GitHub no longer supports password-based authentication. You must choose one of the following secure methods:

11.1.2.1 Personal Access Token (HTTPS)

  • Navigate to:
    GitHub > Settings > Developer settings > Personal access tokens > Fine-grained tokens
  • Click Generate new token.
  • Provide a name, select the repo permission, set an expiry date, and copy the token.
  • When RStudio prompts for a password during your first push, paste the token. Your GitHub username remains unchanged.

This method is straightforward and works reliably across most environments.

11.1.2.2 SSH Key

  • Generate a key:

    ssh-keygen -t ed25519 -C "you@example.com"

    Press Enter to accept the defaults.

  • Copy the contents of ~/.ssh/id_ed25519.pub and add it to GitHub under:
    Settings > SSH & GPG keys > New SSH key

SSH is well-suited for automation and scripting workflows.

11.1.2.3 Git Credential Manager (GCM)

  • On Windows, GCM is bundled with Git.

  • On macOS, install via:

    brew install --cask git-credential-manager

The first push will open a browser window for login. GCM stores your credentials securely in your system keychain and handles token rotation automatically.

Note

To view or clear saved credentials in RStudio:
Tools > Global Options > Git/SVN > Credentials

On Windows, credentials are stored in the Credential Manager.
On macOS, they’re stored in Keychain Access.

11.1.3 Switching between HTTPS and SSH

If you cloned a repository using HTTPS but later want to switch to SSH:

git remote set-url origin git@github.com:<USER>/<REPO>.git

To switch back to HTTPS:

git remote set-url origin https://github.com/<USER>/<REPO>.git

11.1.4 Common Troubleshooting Checklist

Issue Solution
Authentication failed after token paste Token expired or missing repo scope. Generate a new fine-grained PAT.
Prompted for credentials on every push/pull Enable credential caching: git config --global credential.helper manager-core
Permission denied (publickey) with SSH Run ssh -T git@github.com to test. Add key to agent: ssh-add ~/.ssh/id_ed25519.
RStudio ignores saved credentials Upgrade to RStudio ≥ 2023.12. Older versions may not use system keychains correctly.

For platform-specific instructions on credential caching and authentication, refer to GitHub’s official documentation.

11.2 Create a local clone

Cloning a repository means copying its contents including version history from GitHub to your local machine. This allows you to work on the project in RStudio while maintaining version control.

To clone your repository:

  1. In RStudio, navigate to:
    File > New Project > Version Control > Git

  2. Use the HTTPS or SSH link from your GitHub repository (found under the green “Code” button), depending on your chosen authentication method.

  3. Select a local directory for the clone and click Create Project.

Figure 11.1: Clone GitHub Repository

After cloning, the repository’s contents will appear in the Files pane, and a new Git tab will be visible in the RStudio interface.

Figure 11.2: New features in RStudio

By default, the repository includes:

  1. .gitignore: Specifies intentionally untracked files to ignore.
  2. RStudio Project File (.Rproj): Contains metadata for the RStudio project.
  3. ReadMe File (.md): A markdown file with information about the repository.

The gitignore and .Rproj files are created locally when initializing the project in RStudio. These may not yet exist on GitHub, depending on how the repository was originally set up.

Figure 11.3: Changes in Git tab

Before making further changes, switch to the dev branch:

Figure 11.4: Switch branch

At this point, the dev branch mirrors the main branch.

Note

It is recommended to work on a separate development branch (e.g., dev) and reserve the main branch for stable versions. Changes can later be merged into main via a pull request. See Opening a Pull Request for details.

11.3 Creating your first Quarto document

Now that the environment is set up, let’s create our first Quarto document.

In RStudio: Navigate to (File > New File > Quarto Document). Enter a title for your document, accept the default settings, click “OK”, and save the file. You’ll receive a sample Quarto file with the extension .qmd.

By default, Quarto is in Visual Editing mode, which provides a WYSIWYM-style editing interface for Quarto documents. To switch to the Source Editor:

Figure 11.5: Switch mode in RStudio

While the Visual Editor is intuitive and beginner-friendly, the Source Editor offers greater control and transparency. It also makes debugging and version control easier.

Quarto supports two editing modes:

Mode Best suited for How to switch
Visual (WYSIWYM) Quick drafting, beginners, content-first writing Click “Visual”
Source Precise Markdown control, debugging chunk options, version-control diffs Click “Source”

Recommendation: Start in Visual mode if you’re new to Markdown. Switch to Source mode when you need fine-grained control or are preparing code for review or collaboration.

Quarto documents consist of three core components: metadata, text, and code.

Figure 11.6: Quarto sample file

The metadata section is written in YAML and defines properties such as the document title, output format, and creation date.

Exercise

Explore YAML syntax and document properties here.

Add a parameter to the metadata section of your Quarto document to include today’s date in the header. Then click Render in RStudio to generate the HTML output.

    
---
title: "test"
format: html
editor: visual
date: today
---

You can also change the output format using the format parameter. Quarto supports a wide range of formats including HTML, PDF, Word, ePub, Jupyter, and more. See the full list here.

Note

Alternatively, YAML-configurations may be specified on a project level (separate file named _quarto.yml) or on a code chunk level (see YAML Locations).

Code blocks in Quarto begin and end with three backticks. To specify an R code block, use {r} after the opening backticks:

summary(cars)
     speed           dist       
 Min.   : 4.0   Min.   :  2.00  
 1st Qu.:12.0   1st Qu.: 26.00  
 Median :15.0   Median : 36.00  
 Mean   :15.4   Mean   : 42.98  
 3rd Qu.:19.0   3rd Qu.: 56.00  
 Max.   :25.0   Max.   :120.00  

Quarto supports multiple languages including R, Python, Julia, and Observable JS.

You can control how code behaves using execution options. For example:

  • #| echo: false hides the code but still runs it.
  • #| eval: false shows the code but does not execute it.

These options are useful for teaching, documentation, or drafts. A full list is available here.

Exercise

Insert the following code into your Quarto document. Add explanatory text below the chart and render the document as HTML:

library(ggplot2)
ggplot(data=cars, aes(x=speed, y=dist)) +
  geom_point() +
  geom_smooth()

This exercise demonstrates one of Quarto’s key strengths: the ability to combine narrative and code into a single, reproducible document that can be rendered in multiple formats.

11.3.1 Under the hood – the render pipeline

When you click Render, Quarto runs a processing pipeline that converts your .qmd file into the final output document. This process involves three main steps:

  1. knitr (for R) or Jupyter (for Python) executes the code chunks and generates an intermediate Markdown (.md) file. This file combines your code, output, and narrative text.

  2. pandoc converts the Markdown file into the final output format—such as HTML, PDF, or Word—applying layout and styling.

  3. The rendered document opens in the RStudio Viewer or your default browser.

.qmd  -->  knitr(r)/jupyter(py) (code runs) --> .md  -->  pandoc --> HTML | PDF | Word
                                            ▲                    ▲
                                    executes R/Python   LaTeX, styling, layout

You can specify the desired output format in the document’s YAML front matter or in a project-level _quarto.yml configuration file.

Understanding this pipeline is useful for debugging. It helps you identify whether an issue originates from code execution, Markdown conversion, or final rendering.

For more details, see the Quarto Documentation.

11.4 Synchronizing with GitHub

Regular synchronization between your local project and the online repository is essential for version control. Begin by pulling any updates from GitHub.

In RStudio’s Git tab, click the Pull button:

Figure 11.7: Make Pull

Even when working alone, it’s good practice to start each session with a pull to ensure your local copy is up to date.

Next, commit your changes. A commit is a snapshot of your progress, accompanied by a descriptive message.

  1. Save all open files in RStudio.
  2. Click the Commit button in the Git tab.
  3. The commit window shows modified files. Green highlights indicate new content; red highlights indicate deletions. This is called a diff view, showing changes since your last commit.

Select the files to include, write a meaningful commit message, and click Commit.

Alternatively, you can use the terminal:

git add -A
git commit -m "test"

See Figure 11.8.

Figure 11.8: Make Commit

Finally, push your committed changes to GitHub:

Figure 11.9: Make Push

Your online repository should now reflect the latest changes. Make sure you’re viewing the correct branch (e.g., dev) on GitHub.

Figure 11.10: Commit with message ‘test’ was pushed to the dev branch a minute ago

In this example, the dev branch is two commits ahead of main. To share your updates or integrate them into the stable version, open a pull request to merge dev into main.

11.5 Basic markdown syntax

Quarto uses Markdown, a lightweight markup language, to format text. Markdown relies on plain-text symbols to control layout and styling.

11.5.1 Common formatting

  • Bold: Use double asterisks: **Text**Text
  • Italic: Use single asterisks: *Text*Text
  • Headings: Use hash signs # to define heading levels:
# Heading level 1
## Heading level 2
### Heading level 3

11.5.2 Tables

Tables are created using pipes | and dashes -. For example, the numeric operators table in the first lesson was written in Markdown. Figure Figure 11.11 shows how such a table is constructed.

Figure 11.11: How Tables are made in Markdown

11.5.3 Lists

Ordered lists use numbers followed by a period:

Code - Ordered List:
1. item 1
1. item 2
1. Item 3
    + Item 3a
    + Item 3b

Will result in:

  1. Item 1
  2. Item 2
  3. Item 3
    • Item 3a
    • Item 3b

To create an unordered list, use *, -, or +:

Code - Unordered List:
* item 1
* item 2
  * Item 3.1
  - Item 3.2

Which will result in:

  • Item 1
  • Item 2
    • Item 2a
    • Item 2b

11.5.5 Blockquotes

Use > for blockquotes. Nesting is possible with multiple >:

>"Everything is related to everything else, but near things are more related than distant things".
>
>>The phenomenon external to an area of interest affects what goes on inside.

Will result in:

The first law of geography is: “Everything is related to everything else, but near things are more related than distant things”

The phenomenon external to an area of interest affects what goes on inside.

11.5.6 Escaping special characters

Some characters have special meaning in Markdown (e.g., #, *, >, $). To display them literally, prefix with a backslash (\):

  • \##
  • \**

11.5.7 Mathematical notation

Quarto supports LaTeX-style math using dollar signs:

Math. notation example 1:

$x = y$

Result looks like:

x = y

Math. notation example 2:

$\frac{\partial f}{\partial x}$

Result looks like:

\frac{\partial f}{\partial x}

Note

11.5.8 References in Quarto

Quarto supports citation management and automatic bibliography generation using a .bib file, which stores reference metadata in BibTeX format.

11.5.8.1 Create a .bib File

Create a plain-text file using any editor (e.g., Notepad, VS Code, or RStudio) and save it with a .bib extension (e.g., references.bib) in your project folder.

11.5.8.2 Enable BibTeX export in Google Scholar

To export references from Google Scholar, enable BibTeX export in your settings:

Figure 11.12: Enable BibTeX in Firefox 106.0.1

Browser interfaces may vary. Refer to the course discussion forum if you encounter issues.

11.5.8.3 Export BibTeX entries

Once BibTeX export is enabled, a new link labeled “Import into BibTeX” will appear below each reference:

Figure 11.13: BibTeX Link in Firefox 106.0.1

Click the link and copy the BibTeX entry into your .bib file.

11.5.8.4 Integrate references in Quarto

To cite references in your Quarto document:

  1. Specify the .bib file in the YAML metadata:
bibliography: references.bib
  1. Use @<BibTeXKey> to insert citations in your text.
Figure 11.14: Integrate BibTeX reference in Quarto document

11.5.8.5 Render the document

Render the document to HTML. Quarto will process citations and generate a bibliography automatically. Both inline (@key) and bracketed ([@key]) citation styles are supported.

Figure 11.15: Quarto with reference

For a hands-on example, download this Quarto reference example, unzip the folder, and open the .Rproj file in RStudio.

11.6 Extending Quarto with extensions and filters

Quarto’s core is intentionally lightweight, but it can be extended with community-built extensions for advanced customization, automation, and enhanced interactivity.

11.6.1 How It Works Under the Hood

  1. Running quarto add ... downloads the extension into an _extensions/ folder at the root of your project.
    → This folder should be committed to version control so collaborators share the same behavior.

  2. During rendering, Pandoc automatically loads any Lua filters found in _extensions/.

  3. These filters modify the document dynamically — for example, by injecting diagrams or styling callouts.

Why Lua? Pandoc’s native filter language is Lua. Lua filters run without external dependencies and offer high performance.

11.6.2 Example: one-line installation

# Adds a custom callout filter. The Exercise boxes in this module use it.
quarto add coatless-quarto/custom-callout

A catalog of available extensions along with a short guide on writing your own is available in the Quarto Extension Gallery.

To activate filters, list them in your _quarto.yml file:

filters:
  - webr
  - custom-callout

Always check the extension’s README for additional setup instructions.

11.7 Speed up your workflows

Quarto can significantly streamline repetitive reporting tasks. For example, if a client requires daily updates on spatial economic indicators, you can automate the process using Quarto. Instead of manually generating reports, Quarto can compile updated data and visualizations each time the document is rendered.

For real-time data, Alpha Vantage provides financial market data via its Alpha Vantage Rest API. The R package alphavantager enables access to this API directly from R.

This allows you to retrieve real-time stock prices, FX rates, and technical indicators, and integrate them into Quarto reports for automated analysis and visualization.

Note

The free Alpha Vantage tier is limited to 25 API requests per day.

Exercise

Explore a practical example by downloading this draft finance data report. Unzip the folder and open the .Rproj file in RStudio.

The project includes:

  • A .bib file with a BibTeX reference.
  • A .csv file in the data folder, listing over 400 country names, national currencies, and currency codes.
  • A .qmd file with inline R code that renders real-time currency exchange rates in a map.

Review the .qmd file thoroughly before compiling an HTML output. Note that it includes an interactive Leaflet map, making HTML the only supported output format.

Try enhancing the report with an additional spatial indicator, such as a map displaying exchange rates from national currencies to the Euro.

11.8 Self-study

Quarto’s capabilities extend far beyond what we’ve covered in this session. To explore more advanced features, consult the Quarto Guide.

Topics include:

  • Cross-references and figure management
  • Computations in R, Python, Julia, and Observable
  • Output formats such as presentations, dashboards, websites, books, and manuscripts
Note

To find inspiration for your own projects you may consult the Quarto Gallery, which showcases a wide range of real-world examples