Quarto and Rmarkdown tutorial

What is Quarto and Rmarkdown?

Quarto (.qmd) is the new version of RMarkdown (.Rmd). Both are file formats for making dynamic documents integrating R or other coding languages. Quarto and rmarkdown document are markdown document (an easy-to-write plain text format) that contain chunks of embedded R code.

Both Quarto and Rmarkdown files have three main parts:

  • A yamn header, to stablish document formatting. It can be very simple.
  • The markdown text. As in a text editor, but simpler.
  • The R (or other languages) chunks.

Markdown text

Markdown text is one of the simplest ways of writting without spending time in formatting. It is only possible to do some basic formatting. Documents will latter be rendered to other format: html, docx, pdf, epub, …

Some of the things that you can do in markdown are:

Headers
Paragraph Emphasis
Lists
Links
Images
YouTube Videos
Horizontal Rule
Tables

All the tutorials used in this subject were written in Quarto or Rmarkdown. You may see and download the original files at the bitbucket repository: https://bitbucket.org/alfonsogar/tea_daa_tutorials.

Headers

Headers for different levels of titles are put using the right number of #.

# H1
## H2
### H3
#### H4
##### H5
###### H6

H1

H2

H3

H4

H5
H6

Paragraph

To start a new paragraph is necessary to separate by two lines.

First sentence of the first paragraph. 
Second sentence of the first paragraph.

First sentence of the second paragraph.

First sentence of the first paragraph. Second sentence of the first paragraph.

First sentence of the second paragraph.

Emphasis

For enphasizing text there is only options for italics, bold and strikethrough.

Emphasis, aka italics, with *asterisks* or _underscores_.

Strong emphasis, aka bold, with **asterisks** or __underscores__.

Combined emphasis with **asterisks and _underscores_**.

Strikethrough uses two tildes. ~~Scratch this.~~

Emphasis, aka italics, with asterisks or underscores.

Strong emphasis, aka bold, with asterisks or underscores.

Combined emphasis with asterisks and underscores.

Strikethrough uses two tildes. Scratch this.

Lists

For sublists are necessary at least 3 spaces.

1. First ordered list item
2. Another item
    Unordered sub-list. 
1. Actual numbers don't matter, just that it's a number
    1. Ordered sub-list
4. And another item.

* Unordered list can use asterisks
- Or minuses
+ Or pluses
  1. First ordered list item
  2. Another item
    • Unordered sub-list.
  3. Actual numbers don’t matter, just that it’s a number
    1. Ordered sub-list
  4. And another item.
  • Unordered list can use asterisks
  • Or minuses
  • Or pluses

Images

To link an image ![UPV](http://www.upv.es/imagenes/marcaUPVN1.png "Universitat Politècnica de València")

To link an image UPV

Horizontal Rule

Three or more Asterisks or Underscores

***
___

Three or more Asterisks or Underscores



Tables

Tables aren’t part of the core Markdown but they usually work.

There must be at least 3 dashes separating each header cell. The outer pipes (|) are optional, and you don’t need to make the raw Markdown line up prettily. You can also use inline Markdown.

Colons can be used to align columns.

| Tables        | Are           | Cool  |
| ------------- |:-------------:| -----:|
| col 3 is      | right-aligned | $1600 |
| col 2 is      | centered      |   $12 |

You dont need to line up.

Markdown | Less | Pretty
--- | --- | ---
*Still* | `renders` | **nicely**
1 | 2 | 3

Colons can be used to align columns.

Tables Are Cool
col 3 is right-aligned $1600
col 2 is centered $12

You dont need to line up.

Markdown Less Pretty
Still renders nicely
1 2 3

More useful are the functions knitr::kable(), xtable::xtable() or stargazer::stargazer() inside a code chunk (see next chapter).

The R chunks

Rmarkdown is a derivation of markdown that includes R (or other languages) chunks.

A code chunk is included between two lines with three back-ticks each. The first one with r between round brackets (if r language).

 \```{r}
my.table <- trees[1:5, ]
knitr::kable(my.table,
    caption = "Table 1. Five first rows of the trees dataframe from base R.")
             
\```
Table 1. Five first rows of the trees dataframe from base R.
Girth Height Volume
8.3 70 10.3
8.6 65 10.3
8.8 63 10.2
10.5 72 16.4
10.7 81 18.8

It is also possible to include inline code between back-ticks with and r after the first one.

The mean of Iris sepal length is ` r mean(iris$Sepal.Length)`.`

The mean of Iris sepal length is 5.8433333.

There are many chunk options, as echo=FALSE for not showing the code or eval=FALSE to not evaluate the code of a chunk. Also to fix the size or caption of figures. This options should be after a comma after the r inside the curve brackets.

```{r, fig.cap=cap}

cap <- “Figure 1: Relationships between Iris variables.”

plot(iris)

```

Figure 1: Relationships between Iris variables.

Figure 1: Relationships between Iris variables.

 

In Quarto there are some differences. Best explained in the quarto manual. For example you can use “fig-…” to name the figure chunks and “tbl-…” for the tables. Then they can be referenced as @fig-… or @tbl-… .

For chunk options in quarto they can be put inside the chunk commented with “#|” as in the example (see quarto guide for more):

\```{r tbl-trees}
#| tbl-cap: Five first rows of the trees dataframe from base R.
#| tbl-colwidths: [60,40]
kable(head(my.table))
\```
Table 1. Five first rows of the trees dataframe from base R.
Girth Height Volume
8.3 70 10.3
8.6 65 10.3
8.8 63 10.2
10.5 72 16.4
10.7 81 18.8

 

Chunk options by default for all chunks can be set at the begining as in the following example, where by default is stated that code will be not shown, all figures will be saved in the folder “results/figs/”, and the size, format and resolution of figures:

knitr::opts_chunk$set(
  echo = FALSE,                     # Do not show the code
  results = 'asis',                 # Results at the end
  fig.path = "results/figs/",       # Path to save figures
  fig.width = 10,                   # Figures default width
  fig.height = 6.1803,              # Figures default heigth
  dev = "png",                      # png Figures format
  dev.args = list(type = "cairo"),  # png args to improve
  dpi = 100                         # 300 for publication
)

To read more about the chunk options: https://yihui.name/knitr/options/

The Yaml header

At the begining of a rmarkdown document there is always a yaml header, between two lines with three dashes “—”. This header must have at least the output format when rendered:

output: html_document

There are many possible output formats. click the link to see all possible formats and in any of them to see the possible options for this format.

Other useful readings

You may also find the following resources helpful:

Exercises

  1. In RStudio, open a new Quarto (or Rmarkdown) file: file > New file > Quarto document (Spanish: Archivo > Nuevo > Quarto).
  2. Put a title and your name in Author and choose html format.
  3. Look into the document to identify the different parts: yaml header, markdown text and r chunks.
  4. Render the document and see the result.
  5. Render the document in word format and look at the result (in the folder).
  6. Change some chunk options and compare the results (best in html to see the result in the viewer).
  7. Create a new second level chapter (with ##) to include a table.
  8. Create a data frame with the first five rows of the “Iris” data.
  9. Plot the data frame using the kable function.
  10. Put captions to the figure and to the table.

 


 

About this tutorial

Cite as: Alfonso Garmendia (2023) R for life sciences. Chapter 4: Quarto and Rmarkdown. http://personales.upv.es/algarsal/R-tutorials/04_Tutorial-4_R-Quarto-Rmarkdown.html.

Available also in other formats (pdf, docx, …): https://drive.google.com/drive/folders/19w914WCg8BVTVBE_zpgShmg2vpjguV1e?usp=sharing.

Other simmilar tutorials: https://garmendia.blogs.upv.es/r-lecture-notes/

Originals are in bitbucket repository: https://bitbucket.org/alfonsogar/tea_daa_tutorials.

 

Document written in Rmarkdown, using Rstudio.

 

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.