STA1005 - Quantitative Research Methods

Lecture 8: Introduction to Quarto for Research

Damien Dupré | DCU Business School

Objectives

With Posit Cloud, we will see how to create Quarto files (.qmd) to embed text and code output and generate professional outputs.

What do I need to do before starting?

Objectives

Where can I find more resources?

What is Quarto?

The goal is to create a document that is all-in-one:

  • Documents that include source code for their production
  • Notebook AND plain-text flavours
  • Programmatic automation and reproducibility

What is Quarto?

Quarto is an open-source scientific and technical publishing system that builds on standard markdown with features essential for scientific communication.

  • Computations: Python, R, Julia, Observable JS
  • Markdown: Pandoc flavoured markdown with many enhancements
  • Output: Documents, presentations, websites, books, blogs

See https://quarto.org for more details

Two Sides of Quarto Files

On the editor side…

  • Write text in markdown
  • Insert code using R or Python
  • Write “metadata” with YAML

On the output side…

  • Output to HTML
  • Output to PDF
  • Output to Word
  • Many other variations too

Try it by yourself!

️ Your Turn!

In your Posit Cloud:

  1. Create a new Quarto document: File > New File > Quarto Document
  2. A popup will appear, untick “Use visual markdown editor”
  3. Leave everything else as default and click Create
  4. If a warning appears, click Install on the message to install the {rmarkdown} package
  1. Click the blue arrow Render and save the document as report.qmd
05:00

Simple Example

Simple Example

Quarto Structure

Quarto files have 3 different types of content:

1. The YAML

Displayed between two series of --- signs, it corresponds to the metadata shown in the header of the output file (e.g., title, author, date, …) and the type of output (e.g., pdf, html, doc, …)

2. The Text

Written in Markdown style (i.e., text without formatting), it is used as core description in the output document

3. The Code

Inserted in the Quarto file inside “chunks”, the code is processed when creating the output and can display figures and tables

The “YAML”

The Markdown Text

The R Code

Create the Output File

To generate the output file:

  1. Go to File > Render Document (a Render shortcut icon is also displayed in the menu bar)

  1. Give a name to your document, click OK, and voila!

Quarto Editor vs Output

1. The YAML

Output HTML

Simple

---
format: html
---

Default

---
title: "My First Quarto Document"
format: html
date: "1984-03-23"
---

Output HTML

Elaborated

---
title: "My First Quarto Document"
subtitle: "My Subtitle"
author: "Damien Dupre"
date: "1984-03-23"
format:
  html:
    theme: united

execute:
  warning: false

---

Execute Code

Quarto can use R or Python to execute code:

  • R code is executed natively with the {knitr} engine
  • Quarto can also use the Jupyter engine to execute Julia, Python, or other languages that Jupyter supports

Execute Code

If R code is found first, it will default to knitr

---
format: html
---

Or you can force using knitr if you’re mixing R/Python content or if your first code chunk is not R.

---
format: html
engine: knitr
---

You can specify Jupyter to use defaults:

---
engine: jupyter
---

Or a specific Python version

---
engine: python3
---

Execute Code

Quarto also introduces some of these as options for execute: in YAML, for similar concepts in other languages.

---
format: html
execute:
  echo: false
  warning: false
  message: false
---

2. Markdown Style

Emphasising Text

What you type…

this is *italics*

this is **bold**

this is ***bold italics***

What you get…

this is italics

this is bold

this is bold italics

Creating Lists

What you type…

- unnumbered lists
- look like this

1. numbered lists
2. look like this

What you get…

  • unnumbered lists
  • look like this
  1. numbered lists
  2. look like this

Creating Headings

What you type…

# Level 1 heading

## Level 2 heading

### Level 3 heading

What you get…

Level 1 heading

Level 2 heading

Level 3 heading

LaTeX Equations

What you type…

$$
JS_i = b_0 + b_1 Salary_i + b_2 Perf_i + e_i
$$

$$
e_{i} \sim \mathcal{N}(0, \sigma_{i})
$$

What you get…

\[ JS_i = b_0 + b_1 Salary_i + b_2 Perf_i + e_i \]

\[ e_i \sim \mathcal{N}(0, \sigma_i) \]

Markdown Example

Example of a markdown document…

## Introduction

Welcome to my **awesome** class. You 
will learn all kinds of useful things 
about Quarto.

- Markdown is simple
- You can add R code
- You can add $\LaTeX$ inline
- You can add LaTex equations:

$$y=ax+b$$

Here’s what the output looks like…

Introduction

Welcome to my awesome class. You will learn all kinds of useful things about Quarto.

  • Markdown is simple
  • You can add R code
  • You can add \(\LaTeX\) inline
  • You can add LaTeX equations:

\[y=ax+b\]

️ Your Turn!

In Posit Cloud, with the file that you have previously created:

  1. Remove all content except the YAML

  2. Modify the YAML to include:

---
format: html
execute:
  echo: false
  warning: false
---
  1. Write a sentence about your emotions (positive and negative) triggered by R, use * and ** to highlight some part of your text in italic and bold
  2. Add a section title with ## and a subsection title with ###
  3. Click Render once finished
05:00

3. The R Code Chunks

Anatomy of a Code Chunk

```{r}
#| label: organisation-beta-lm
#| echo: false
model <- lm(formula = js_score ~ salary + perf, data = organisation_beta)
```
  • Has 3x backticks on each end ```
  • Place engine (r) between curly braces {r}
  • Place options underneath, behind the #| (hashpipe): #| option1: value

First Code Chunk

In the first code chunk, all the actions that will be applied to the following chunks will be added (e.g., code options, libraries used, data downloaded, …).

```{r}
#| label: setup
#| include: false

# libraries
library(tidyverse)
  
# data
organisation_beta <- read_csv("/cloud/project/organisation_beta.csv")
```

Code Chunk Options

Chunk output can be customised with hashpipe options (i.e., arguments set after the #|). Above, we use 1 argument:

  • #| include: false prevents code and results from appearing in the finished file. Quarto still runs the code in the chunk, and the results can be used by other chunks.

Additional options can be turned on only for one chunk:

  • #| results: asis will display the output of the code as regular text

See the Quarto Reference Guide for a complete list of chunk options.

Figures in the Output Document

As long as the package {tidyverse} is loaded and the data object created in the first setup chunk, then a ggplot visualisation can be used in a separate chunk:

---
title: "Untitled"
format: html
execute:
  echo: false
  warning: false
---

```{r}
#| label: setup
#| include: false

library(tidyverse)

organisation_beta <- read_csv("/cloud/project/organisation_beta.csv")
```

# My Section Title

My text followed by my figure.

```{r}
ggplot(organisation_beta) +
  aes(salary, js_score) +
  geom_point()
```

Working with Code

To display the output of your code in the final document, just include your code in a chunk:

```{r}
lm(formula = js_score ~ salary + perf, data = organisation_beta)
```

Call:
lm(formula = js_score ~ salary + perf, data = organisation_beta)

Coefficients:
(Intercept)       salary         perf  
  -49.48511      0.00187      0.08285  

Working with Code

Remember, when the code results in creating an object, while the object is created, no output is printed in the final document:

```{r}
model <- lm(formula = js_score ~ salary + perf, data = organisation_beta)
```

Working with Code

To create an object and print your code in the same chunk, the name of the object has to be included in the chunk. This will print the content of the object:

```{r}
model <- lm(formula = js_score ~ salary + perf, data = organisation_beta)
  
model
```

Call:
lm(formula = js_score ~ salary + perf, data = organisation_beta)

Coefficients:
(Intercept)       salary         perf  
  -49.48511      0.00187      0.08285  

Visualisation Specific Options

Some chunk options are specific to visualisation outputs:

  • fig-cap: “Example Caption”
  • fig-height: 2
  • fig-width: 12

Note, the default unit for height and width is inches.

```{r}
#| fig-cap: "Example Caption"
#| fig-height: 2
#| fig-width: 12

ggplot(organisation_beta) +
  aes(salary, js_score) +
  geom_point()
```

Visualisation Specific Options

```{r}
#| fig-cap: "Example Caption"
#| fig-height: 2
#| fig-width: 12

ggplot(organisation_beta) +
  aes(salary, js_score) +
  geom_point()
```

Example Caption

Live Demo

️ Your Turn!

In your report.qmd document:

  1. Create a first code chunk called setup. In this chunk, load the {report} packages and create your data object with the following code:
organisation_beta <- read.csv("/cloud/project/organisation_beta.csv")
  1. Create a second code chunk. In this chunk, run the following linear regression and add #| results: asis in its options:
lm_js <- lm(formula = js_score ~ salary + perf, data = organisation_beta)

report(lm_js)
05:00

️ Your Turn! (continued)

  1. Create a third code chunk. In this chunk, include the following visualisation:
ggplot(organisation_beta) +
  aes(salary, js_score) +
  geom_point() +
  geom_smooth(method = "lm") +
  theme_bw() +
  labs(
    x = "Employee Salary (Eur)",
    y = "Employee's Job Satisfaction"
  )
  1. Render the document to observe its structure
03:00

Professional Websites

Books

Slide Decks

CV

Academic Papers

5. Quarto Journal Templates

Quarto Journal Templates

The Quarto team has developed several Journal formats and made them available within the quarto-journals GitHub organization. These formats include the following Journal/Publisher:

  • Association of Computing Machinery
  • American Chemical Society
  • American Geophysical Union
  • Biophysical journal
  • Elsevier Journals
  • American Statistical Association
  • Journal of Statistical Software

Many more formats will be added over time.

Quarto Journal Templates

The quarto use template command can be used to create an article from one of these formats from the terminal (and not the console). For example:

Terminal
quarto use template quarto-journals/acm
quarto use template quarto-journals/acs
quarto use template quarto-journals/agu
quarto use template quarto-journals/biophysical-journal
quarto use template quarto-journals/elsevier
quarto use template quarto-journals/jasa
quarto use template quarto-journals/jss
quarto use template quarto-journals/plos

Live Demo

️ Your Turn!

  1. Create a new quarto-journals document using one of the following templates from the terminal:
Terminal
quarto use template quarto-journals/acm
quarto use template quarto-journals/acs
quarto use template quarto-journals/agu
quarto use template quarto-journals/biophysical-journal
quarto use template quarto-journals/elsevier
quarto use template quarto-journals/jasa
quarto use template quarto-journals/jss
quarto use template quarto-journals/plos

Note

Choose Y when asked if you trust the authors of this template and choose a directory name.

  1. Render the default .qmd document obtained to observe it.
05:00

️ Your Turn!

In this new .qmd document:

  1. Remove everything except the YAML

  2. Create a first setup chunk. In this chunk, load the {report} packages and create your data object with the following code:

organisation.beta <- read_csv("/cloud/project/organisation_beta.csv")
  1. Create a second code chunk. In this chunk, run the following linear regression and add #| results: asis in its options:
lm_js <- lm(formula = js_score ~ salary + perf, data = organisation_beta)

report(lm_js)
05:00

️ Your Turn! (continued)

  1. Install the package {tidyverse} and add library(tidyverse) in the setup chunk
  2. Create a third code chunk. In this chunk, include the following visualisation:
ggplot(organisation_beta) +
  aes(salary, js_score) +
  geom_point() +
  geom_smooth(method = "lm") +
  theme_bw() +
  labs(
    x = "Employee Salary (Eur)",
    y = "Employee's Job Satisfaction"
  )
  1. Render the document to observe its structure
03:00

6. Quarto Website Templates

Quarto Websites

Quarto Websites are a convenient way to publish groups of documents. Documents published as part of a website share navigational elements, rendering options, and visual style.

Website navigation can be provided through a global navbar, a sidebar with links, or a combination of both for sites that have multiple levels of content. You can also enable full text search for websites.

Quarto Websites

Unfortunately, Quarto Websites cannot be visualised on Posit.cloud as it is not your computer.

If you want to give it a go:

  1. Install R on your own computer from https://cran.r-project.org/
  2. Install RStudio on your own computer from https://posit.co/download/rstudio-desktop

Note

Among the Integrated Development Environment (IDE) there is also VScode, Positron, and many more.

  1. Install Quarto on your own computer from https://quarto.org/

Quarto Websites

Terminal
quarto create project website mysite

Creates a new website project from the Terminal. This website project is initiated by a folder called mysite located on the root of your terminal.

Quarto Websites

The folder contains only 4 files:

  • _quarto.yml designs the overall style and the navbar
  • index.qmd corresponds to the homepage
  • about.qmd is another page
  • styles.css is for additional style not defined in _quarto.yml

Improve your Website:

Quarto Websites

Terminal
quarto preview mysite

These commands are used to render the website by converting all the .qmd files to .html files stored in a _site folder.

The website preview will open in a new web browser. As you edit and save index.qmd (or other files like about.qmd) the preview is automatically updated.

Demonstration

Warning

Only run on your own computer if R, RStudio (or equivalent), and Quarto are installed.

  1. In the Terminal window, run the following instruction:
Terminal
quarto create project website mysite
  1. and
Terminal
quarto preview mysite

Demonstration

  1. In the _quarto.yml file, simply change the output directory folder to a folder named docs as follows:
_quarto.yml
project:
  type: website
  output-dir: docs

Then render the website:

Terminal
quarto render mysite

Demonstration

Your website default folder should look like that →

Note

The old folder _site will not be used any more and is now useless.

Demonstration

Add a .nojekyll file to the root of your repository that tells GitHub Pages not to do additional processing of your published site using Jekyll (the GitHub default site generation tool).

You can create it from the terminal when the website folder is the current directory:

Bash or zsh
touch .nojekyll
CMD
type nul > .nojekyll
PowerShell
ni .nojekyll

Demonstration

In GitHub, just drag and drop all the files at once like this:

Finally, click Settings -> Pages choose:

  • main branch
  • /docs folder
  • and Save


Thanks for your attention

and don’t hesitate to ask if you have any questions!