8  Quarto-PDF

8.1 Before you start

To author a full journal article using Quarto, you’ll need to acquire or have familiarity with the following skills:

Important
  • Basic knowledge of how Quarto works (Official Website).
  • Create figures using R (any R package, like ggplot2)
  • Create tables using R with select R packages that are compatible with Latex-PDF output (e.g., huxtable, kableExtra, modelsummary, gtsummary)
  • Familiarity with basic debugging of Latex codes (highly preferable).

Before delving into this chapter, carefully consider the time and effort required to master these skills. Ensure the investment aligns with your goals and priorities.

While you can generate a PDF article without LaTeX expertise, it’s strongly advised to familiarize yourself with LaTeX debugging. This not only aids in customizing the article format but also prepares you for potential compilation errors you might face.

8.2 Preparation

Before diving in, please do the followings:

  • Go here and download all the files including sample_to_pdf.qmd, which we refer to as the sample rmd file throughout this chapter.

  • Alternatively, you can clone this Github repository and go to the Resources/PDF-Quarto/ folder.

  • Open RStudio (or any other software you you may be using like VS code) and knit sample_to_pdf.qmd to produce sample_to_qmd.pdf, which we refer to as the sample PDF file.

  • Install the following packages if you have not

    • knitr
    • Rmarkdown
    • tidyverse
    • modelsummary
    • gtsummary
    • huxtable
    • kableExtra

8.3 YAML header

A Quarto file starts with a YAML header, which lets you specify things like

  • paper title
  • authors (with affiliations and other subsidiary information)
  • date
  • abstract

It also lets you specify various aspects of the output PDF file including

  • whether to include table of contents (toc)
  • the depth of table of contents (toc_depth)
  • whether to number sections or not (number_sections)
  • how to display plots and tables
    • size
    • alignment

This is also where you specify what files you use as bibliography, citation style, among other things. Important ones will be introduced later.

Here is an example YAML header, which you can see in sample_to_pdf.qmd file.

Full list of options can be found here. More detailed explanation of some of the output options will be provided later individually when the relevant topics are discussed.

8.4 Control the style and format

You can insert raw tex codes as a file or text to the tex file that would be later compiled to a pdf (see the official instruction here).

For example, the sample qmd file includes “preamble.tex” in the header by having the following lines in the YAML.

“preamble.tex” has the following as its content.

For example, it adds line numbers to the output pdf file with

\usepackage{lineno}
\linenumbers

8.5 Using existing journal templates

To streamline the formatting and styling of your article, first check if a template for your target journal is available. Browse the list of existing journal templates on this GitHub repository. If the desired template is available, you are in luck! Utilizing it can save significant time since these templates are crafted to meet journal specifications.

Let’s walk through the process of using the American Geophysical Union (agu) template. To get started with the AGU journal template using Quarto:

  1. Install the Extension: Follow the instructions provided on the GitHub page. Begin by installing the extension through your terminal:

    quarto add quarto-journals/agu
  2. Set Up Your Project: Navigate to the directory where you want to create your new project using the cd command. Then, initialize the template:

    quarto use template quarto-journals/agu

    This action will display an output on your terminal, similar to:

    Here, input the desired directory name (in this example, ‘agu-ex’). A folder with the given name will be created in your current directory.

  3. Start Writing: Now you’re good to go! Open the template .qmd file in the newly created directory and begin drafting your article.

Important
  • Please do not delete the “_extensions” folder, which includes files that are necessary to a produce AGU-compatible PDF.

8.6 Citations and References

8.6.1 Set up

Begin by preparing a file that contains all your references. In your document’s YAML header, specify the bibliography file:

bibliography: bibliography file name

There are multiple formats and systems available for bibliographies, such as BibLaTeX/BibTex (.bib), CSL-JSON (.json), and EndNote (.enl). among others.

In this illustration, we are employing a .bib file. If our bibliography file is titled bibliography.bib, the YAML header would look like:

When knitting to PDF, the references will be positioned at the conclusion of the document, as documented (see here). Append # References {-} to the tail end of your .qmd file. This creates a “References” section heading where all the citations will be listed. Including {-} adjacent to the section header ensures the References section remains unnumbered. This is particularly useful if you have activated section numbering in the YAML header with number-sections: true. Without {-}, the “References” section would be automatically numbered, which is often not desired in academic and professional documents.

Note
  • See the sample qmd file to see how bibliography file is specified in the YAML header
  • Confirm that the Reference section of the sample qmd and PDF files

8.6.2 Cite and create references

To cite, use the following syntax:

  • @reference_name to print “author names (year)” in the output WORD file
  • [@reference_name] to print “(author names, year)” in the output WORD file
  • [@reference_name_1; @reference_name_2] to print “(author names, year; author names, year)” in the output WORD file
  • [-@reference_name] to print just year

reference_name is the very first entry of a .bib file as in

If you are using CSL json file, then it is the id of an entry as in

The cited items are automatically added to the reference following the specified style (see the next section).

Note
  • See the Introduction and Reference sections in the sample qmd and PDF files to confirm this rule.
  • Comment out bibliography: bibliography.bib and uncomment bibliography: bibliography.json, knit again, and check citations and references are still there. This is just an illustration of using a different bibliography file (CSL-json file).

8.6.3 Citation and Reference Style

You can change the citation and reference style using Citation Style Language. Citation style files have .csl extension.

  1. Obtain the csl file you would like to use from the Zotero citation style repository.

  2. Place the following in the YAML header:

csl: csl file name 
  1. Then, when knitted, citations and references styles reflect the style specified by the csl file

Currently, the csl style is set to qje.csl (citation style language for The Quarterly Journal of Economics) as below

Citation and references styles in the output PDF file follows the rules for the QJE.

Citation style for QJE

Reference style for QJE

Now, comment csl: qje.csl and uncomment csl: pnas.csl so that the CSL for the Proceedings of the National Academy of Sciences (PNAS) is used, and then knit the sample qmd file.

You can now see that the citation style no longer respects the rules I mentioned above and also the reference style follows that of PNAS. This is because PNAS uses only numbers, but not author names or years.

Citation style for PNAS

Reference style for PNAS

8.7 Tables (Cross-referenced)

  1. Create a table using any R package that can produce latex tables.

  2. Add an R code chunk like this:

```{r}
#| label: tbl-id
#| tble-cap: "Sample table caption"
table_sample
```
  • table_sample is the name of the table created on R.
  • Sample table caption is the caption of the table in the output PDF file
  • tbl-id is the chunk label you can use to cross-reference the table
  1. Use @tbl-id in the Quarto file to cross-reference the table (table numbering in the output PDF file is automatic).

The table in the PDF will have Sample table title as the tabe title. @tab-sample will append “Table” automatically. So, if you have Table @tbl-sample in your qmd file, then you will see “Table Table figure-number” in the output PDF file.

Important
  • label needs to start with tbl-, otherwise, the output of the chink would not be recognized as a table.
  • You cannot use _ in label (- is allowed). Cross-referencing would not work if label includes _.

8.7.1 Packages to create tables


8.7.1.1 Simple table from a data.frame

There are many R packages that let you create tables that are compatible with Latex. For example, you can use the kableExtra and huxtable package to create tables from a data.frame-like R objects from scratch. Here is an example code using the huxtable package.

library(huxtable)

head(iris, 10) %>%
# Create a huxtable
as_hux() %>%
# Add some basic styling
set_background_color(row = 1, value = "lightgray") # Background color for header
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
5.1 3.5 1.4 0.2 setosa
4.9 3   1.4 0.2 setosa
4.7 3.2 1.3 0.2 setosa
4.6 3.1 1.5 0.2 setosa
5   3.6 1.4 0.2 setosa
5.4 3.9 1.7 0.4 setosa
4.6 3.4 1.4 0.3 setosa
5   3.4 1.5 0.2 setosa
4.4 2.9 1.4 0.2 setosa
4.9 3.1 1.5 0.1 setosa

The gt package does not work as well with Latex as it does with the html output1. In academic journals, fancy looking tables are not necessary. kableExtra and huxtable are likely to be very much sufficient.


8.7.1.2 Regressions results and summary tables

For regression results and summary statics, the modelsummary and gtsummary2 packages are particularly convenient and useful. For example, the modelsummary package lets you create regression results and summary statistics tables via the modelsummary() function and summary statistics tables via the datasummary() function3. For the gtsummary package, their respective corresponding functions are tbl_regression and tbl_summary. For regression results tables, the stargazer package is also a viable option. It is less capable in creating summary statistics tables than modelsummary and gtsummary.

Here are example R codes of using the modelsummary package to create regression results and summary statistics tables.

Regression table

#--- regressions ---#
lm_1 <- fixest::feols(mpg ~ hp + cyl, data = mtcars)
lm_2 <- fixest::feols(mpg ~ hp + cyl + wt, data = mtcars)
lm_3 <- fixest::feols(mpg ~ hp + cyl + wt, cluster = ~ vs, data = mtcars)

#--- create a regression results table ---#
modelsummary::modelsummary(
  list(lm_1, lm_2, lm_3),
  gof_omit = "IC|Log|Adj|F|Pseudo|Within"
)

This is how the table would appear on the output PDF file.

Summary statistics table

modelsummary::datasummary(
  mpg + hp + cyl ~ Mean + SD,
  data = mtcars
)

This is how the table would appear on the output PDF file.

8.7.1.3 Further modifying regression and summary statistics tables

You can modify (fine-tune) the output of modelsummary or gtsummary using the huxtable package if you are not satisfied. For the modelsummary package, this can be done by using output = "huxtable" and then use huxtable functions for modifications. Here is an example code.

library(huxtable)

modelsummary(list(lm_1, lm_2, lm_3),
 output = "huxtable",
 gof_omit = "IC|Log|Adj|F|Pseudo|Within",
 stars = TRUE
) %>%
# Bold the header row
# set_bold(row = 1) %>%
# Border at the bottom of the table
set_bottom_border(row = nrow(.), value = 0.4) %>%
# Center-align the header
set_align(1, everywhere, value = "center") %>%
# Set font size to 10
set_font_size(value = 10) 

For the gtsummary package, you can apply as_hux_table() and then modify the table.

Here is an example code for using the kableExtra package.

modelsummary(list(lm_1, lm_2, lm_3),
  output = "kableExtra",
  gof_omit = "IC|Log|Adj|F|Pseudo|Within",
  stars = TRUE
) %>%
  kableExtra::add_header_above(
    c(" " = 1, "Model (se not clustered) " = 2, "Model (se clustered)" = 1)
  )

8.7.2 Avoid “Not in outer par mode” error

For some tables, you may encounter the following error while compiling the tex file created in the process (see here).

You can avoid this problem by adding the following tex codes in the preamble.

\usepackage{float}
\floatplacement{figure}{H}
\floatplacement{table}{H}

In the sample qmd file, this is done by having the above lines in a file named “preamble.tex” and calling it in the YAML like below.

Of course, with these float options, tables and figures will appear exactly where they are created or called in the qmd file.

8.8 Figures (Cross-referenced)

8.8.1 Figures created internally

You can create plots within a Quarto file and display them in the output PDF file. Here are the steps.

  1. Create a plot using R

  2. Add an R code chunk like this:

```{r}
#| label: fig-sample
#| fig-cap: "Sample figure title"
figure_sample 
```
  • figure_sample is a plot.
  • fig-cap: "Sample figure title" adds Sample figure title as the caption of the figure
  • fig-sample is the figure id used for cross-referencing
  1. Use @fig-sample (the chunk label specified in label: fig-sample) in the qmd file to cross-reference the figure (figure numbering in the output PDF file is automatic).

The figure in the PDF will have Sample figure title as the figure title. @fig-sample will append “Figure” automatically. So, if you have Figure @fig-sample in your qmd file, then you will see “Figure Figure figure-number” in the output PDF file.


Rmarkdown

PDF
Important
  • Do not forget to have fig- at the beginning of the chunk label as in label: fig-sample in the R code chunk option. Otherwise, the plot will not be recognized as a figure in the output PDF file and cross-referencing will not work even though the figure will be displayed.
  • You cannot use _ in the chunk label (- is allowed). Cross-referencing would not work if the label includes _.
  • location of the caption

8.8.2 Importing pre-made figures

To incorporate pre-made images or figures into your Quarto document, especially when they are not generated within the itself, you can use the knitr::include_graphics() function.

You can use the knitr::include_graphics() function to insert your desired image.

```{r }
#| label: "fig-your-label"
#| fig-cap: Your Figure Caption
knitr::include_graphics("path_to_your_image.png")
```

Imported figures can be cross-referenced just like figures generated within R, as demonstrated previously.


Rmarkdown

WORD

8.8.3 Figure placement

8.8.4 Change the size of the figure

You can control the size of the plots in the output PDF file using the out.width or out.height option in the R code chunk.

Try
  • Change out.width to 2 and see what happens to the output WORD file.
  • Remove the fig.cap option and see what happens to the output WORD file.
  • Change the dpi value to 100 see what happens to the output WORD file.

8.9 Mathematical equations

You can take the full advantage of Latex’s advanced math typesetting capability to write mathematical equations unlike the rmd-to-WORD option.

8.9.1 Math equation with different environments

To type mathematical equations, you can simply put bare latex math expressions in the qmd file. Alternatively, you could enclose the math expressions with a special syntax for printing tex expressions like below.

```{=tex}
Math
```

Let’s take a look at several popular math environments.


equation environment

```{=tex}
\begin{equation}
\bar{y} = \sum_{i=1}^n y_i
\end{equation}
```

prints like below in the output PDF file.

\[ \begin{equation} \bar{y} = \sum_{i=1}^n y_i \end{equation} \]


cases environment inside an equation environment

```{=tex}
\begin{equation}
y_{j,i} =
  \begin{cases}
  \alpha_{j,i} + \beta_{j,i} N + \gamma_{j,i} N^2 + \varepsilon_{j,i} \, ,& N < \tau_{j,i} \\
  \alpha_{j,i} + \beta_{j,i} \tau_{j,i} + \gamma_{j,i} \tau_{j,i}^2 + \varepsilon_{j,i} \, ,& N \ge \tau_{j,i}
  \end{cases}
\end{equation}
```

\[ \begin{equation} y_{j,i} = \begin{cases} \alpha_{j,i} + \beta_{j,i} N + \gamma_{j,i} N^2 + \varepsilon_{j,i} \, ,& N < \tau_{j,i} \\ \alpha_{j,i} + \beta_{j,i} \tau_{j,i} + \gamma_{j,i} \tau_{j,i}^2 + \varepsilon_{j,i} \, ,& N \ge \tau_{j,i} \end{cases} \end{equation} \]


align environment

```{=tex}
\begin{align}
 AR(p): Y_i &= c + \epsilon_i + \phi_i Y_{i-1} \dots \\
 Y_{i} &= c + \phi_i Y_{i-1} \dots
\end{align}
```

prints like below in the output PDF file.

\[ \begin{align} AR(p): Y_i &= c + \epsilon_i + \phi_i Y_{i-1} \dots \\ Y_{i} &= c + \phi_i Y_{i-1} \dots \end{align} \]

8.9.2 Cross-reference equations

In the official Quarto documentation, they present an example of cross-referencing an equation for a math written between \(\$\$\) and \(\$\$\), which is another way of writing an equation. However, the complexity of equations that can be written in this manner is rather limited. As of now (2024-09-11), if you try this way of cross-referencing for environments like align, it would not work.

This one works.

```{=tex}
$$
\bar{y} = \sum_{i=1}^n y_i
$$ {#eq-simple}
```

But, this one would not (Try it yourself. It is not tested in our sample qmd file because it would cause a compilation error.).

```{=tex}
$$
\begin{align}
 AR(p): Y_i &= c + \epsilon_i + \phi_i Y_{i-1} \dots \\
 Y_{i} &= c + \phi_i Y_{i-1} \dots
\end{align}
$$ {#eq-align}
```

This one neither.

```{=tex}
$$
 AR(p): Y_i &= c + \epsilon_i + \phi_i Y_{i-1} \dots \\
 Y_{i} &= c + \phi_i Y_{i-1} \dots
$$ {#eq-align}
```

Instead, we could cross-reference equations the Latex way, taking full advantage of the fact that raw tex codes are accepted. For example, this would work.

```{=tex}
\begin{align}
Y_z & = f_z(S) + g_z(N) + h_z(X,Y) + \varepsilon_z \notag \\
& = \sum_{i=1}^k \phi_k(S) + g_z(N) + h_z(X,Y) + \varepsilon_z \label{eq-align}
\end{align}
```

Then, use \ref{eq-align} to cross-reference it. You can confirm this in the Statistical Model section of the sample qmd file.


qmd

PDF

8.9.3 In-line math

To write a mathematical expression in line, you can enclose a math expression by $ like below.

Our model is written as $Y_z = f_z(S) + g_z(N) + h_z(X,Y) + \varepsilon_z$.

This should appear like below in the output PDF file.

Our model is written as \(Y_z = f_z(S) + g_z(N) + h_z(X,Y) + \varepsilon_z\).


qmd

PDF

  1. e.g., if you use the gt package, some style changes would not be reflected on the PDF file (see here). It works perfectly fine when the output is an html file.↩︎

  2. You can also use the stargazer package.↩︎

  3. The modelsummary package is more economist-friendly (or social scientists) than gtsummary.↩︎