Computations

Introduction

This guide provides the essentials for integrating R with Quarto. Perfect for R users of all levels, this tutorial covers:

  • Setup: Quick steps to install rmarkdown and prepare your environment.
  • Code Execution: Learn to run and control R code blocks within your Quarto documents.
  • Inline Code: Embed dynamic R code into your text for real-time updates.
  • Advanced Features: Explore chunk options and formatting to enhance your documents.


Prerequisites

Install the rmarkdown R package.

install.packages("rmarkdown")

Code Block

Executable R code blocks syntax: ```{r}. Example:

---
title: "R Code"
---

Example of code: 

```{r}
print("Hellow World")
```

Inline Code

  • Embed live code in markdown with a single tick (`) instead of triple (```).
  • Example: Set radius in a code block and reference it in text with inline code.
```{r}
radius <- 5
```

The radius of the circle is `{r} radius`

Use I() function for markdown syntax in inline expressions:

This is `{r} I("**bold**")`

Rendering

Read rendering Quarto documents containing Python or R code blocks.

Chunk Options

In Quarto, chunk options are placed in comments at the top of code chunks, not in the chunk-start line:

```{r}
#| echo: false
#| fig-cap: "Air Quality"

library(ggplot2)
ggplot(airquality, aes(Temp, Ozone)) + 
  geom_point() + 
  geom_smooth(method = "loess", se = FALSE)
```

Options use YAML syntax, with !expr for R code in values as follow:

#| fig-cap: !expr 'paste("Air", "Quality")'

Output Formats

In Quarto, use the format key instead of output:

R Markdown

title: "My Document"
output:
  html_document:
    toc: true
    number_sections: true
    css: styles.css

Quarto

title: "My Document"
format:
  html:
    toc: true
    number-sections: true
    css: styles.css

Quarto aligns with Pandoc, using - in options.

Data Frames

Control default data frame printing in your document with the df-print option. Choices include:

  • default: Uses the data frame’s standard S3 method.
  • kable: Generates a Markdown table via knitr::kable().
  • tibble: Displays a plain text table with the tibble package.
  • paged: Creates an HTML table with paging for large data via rmarkdown::paged_table().

To set paged printing for data frames:

---
title: "Document"
format: 
   html:
     df-print: paged
---

Knitr Options

For Knitr execution, set default chunk options in YAML:

---
title: "My Document"
format: html
knitr:
  opts_chunk: 
    collapse: true
    comment: "#>"
    R.options:
      knitr.graphics.auto_pdf: true
---

Use opts_knit for global settings. R.options sets temporary R options() pre-execution. Apply these settings document-wide or in a project’s _quarto.yml or _metadata.yml.

References