Tutorial: Computations
You can work through this tutorial using R or Python code examples. Select your preferred language:
You’ve selected to see examples in R. You can toggle to Python whenever you like throughout the guide.
You’ve selected to see examples in Python. You can toggle to R whenever you like throughout the guide.
Overview
Quarto supports executable code cells within markdown. This allows you to create fully reproducible documents and reports—the code required to produce your output is part of the document itself, and is automatically re-run whenever the document is rendered.
In this tutorial, you’ll learn how to author fully reproducible computational documents with Quarto in Positron.
You’ll learn how to:
Run code cells interactively in the Console
Control code output, including hiding code
Control figure output including captions and layout
Add new code cells and get help with code cell options
Use values from your code cells in markdown text
Setup
Be sure that you have installed the
rmarkdown
andtidyverse
packages:install.packages("rmarkdown") install.packages("tidyverse")
Download
computations.qmd
below and open it in Positron.Run the Quarto: Preview command, use the keyboard shortcut , or use the Preview button (
) in the editor toolbar, to render and preview the document.
Install the
jupyter
andplotnine
packages using your preferred method. For example, withpip
:pip install jupyter plotnine
Download
computations.qmd
below and open it in Positron.Run the Quarto: Preview command, use the keyboard shortcut , or use the Preview button (
) in the editor toolbar, to render and preview the document.
Cell Execution
As you author a document you may want to execute one or more code cells without re-rendering the entire document. You can do this using the Run Cell button above the code cell. Click the button, run the command Quarto: Run Cell, or use the shortcut , to execute the current cell in the Console:
In addition to running a single code cell, there are a variety of other commands and keyboard shortcuts available:
Quarto Command | Keyboard Shortcut |
---|---|
Run Cell | |
Run Current Code | |
Run Next Cell | |
Run Previous Cell | |
Run Cells Above | |
Run Cells Below | |
Run All Cells |
A good approach to troubleshooting the code in your document is to restart your Console (), and Quarto: Run All Cells (). This emulates Quarto’s approach to executing the code in your document: starting a clean session and executing code cells from top to bottom.
Cell Output
By default, the code and its output are displayed within the rendered document.
However, for some documents, you may want to hide all of the code and just show the output. To do so, specify echo: false
in document header.
---
title: Quarto Computations
echo: false
---
Preview again to see your updates reflected. The result will look like the following.
You might want to selectively enable code echo
for some cells. To do this add the echo: true
option to a code cell. Try this with the cell labelled scatterplot
.
#| label: scatterplot
#| echo: true
ggplot(mpg, aes(x = hwy, y = cty, color = cyl)) +
geom_point(alpha = 0.5, size = 2) +
scale_color_viridis_c() +
theme_bw()
#| label: scatterplot
#| echo: true
(="hwy", y="cty", color="cyl"))
ggplot(mpg, aes(x+ geom_point(alpha=0.5, size=2)
+ scale_color_continuous()
+ theme_bw()
)
Preview the document again and note that the code is now included for the scatterplot
cell.
The echo
option controls whether the source code itself is shown in the rendered document. Other options control the display of other aspects of code cells. Like echo
they can be set in the document header or overridden in code cells:
output
: show output of the code like figures, tables, text output, etc. (defaulttrue
)warning
: show warnings produced by the code (defaulttrue
)include
: show anything, a catch-all for the code itself, output, and warnings (defaulttrue
)eval
: whether to execute the code or not (defaulttrue
)error
: whether execution should continue after an error and the error should be displayed (defaultfalse
)
You can read more about these options in Execution options.
Code Appearance
There are lots of other options to tweak the appearance of code in your document. For example, an alternative to showing or hiding code is to use code folding.
#| label: scatterplot
#| echo: true
#| code-fold: true
ggplot(mpg, aes(x = hwy, y = cty, color = cyl)) +
geom_point(alpha = 0.5, size = 2) +
scale_color_viridis_c() +
theme_bw()
#| label: scatterplot
#| echo: true
#| code-fold: true
(="hwy", y="cty", color="cyl"))
ggplot(mpg, aes(x+ geom_point(alpha=0.5, size=2)
+ scale_color_continuous()
+ theme_bw()
)
Code cells in the rendered document are placed under a collapsed “Code” button, which readers can expand at their discretion.
As another example, you can add line numbers to your code cells with the code-line-numbers
:
#| label: scatterplot
#| echo: true
#| code-fold: true
#| code-line-numbers: true
ggplot(mpg, aes(x = hwy, y = cty, color = cyl)) +
geom_point(alpha = 0.5, size = 2) +
scale_color_viridis_c() +
theme_bw()
#| label: scatterplot
#| echo: true
#| code-fold: true
#| code-line-numbers: true
(="hwy", y="cty", color="cyl"))
ggplot(mpg, aes(x+ geom_point(alpha=0.5, size=2)
+ scale_color_continuous()
+ theme_bw()
)
The options available for code cells depend on the engine used to execute the code cells. You can read more about how Quarto chooses an engine in Engine Binding.
If you’ve been working through this tutorial with R, you have been using the knitr
engine. See Knitr Cell Options documentation for the complete list of available code cell options.
If you’ve been working through this tutorial with Python, you have been using the jupyter
engine. See the Jupyter Cell Options documentation for the complete list of available code cell options.
Many code cell options can also be set in the document header to apply the option to all code cells. For instance, you could fold all code cells in the document by adding the code-fold
option to the document header:
---
title: "Quarto Computations"
format:
html:
code-fold: true
---
To understand which options can be set in the document header, look at the Reference for the format you are using. For instance, code-fold
can be set in the document header because it is listed as an HTML format option. You’ll learn more about when to set document header options nested under a format versus at the top level in the next tutorial: Authoring.
You can see examples of other options that control code appearance in the HTML format in the Guide page HTML Code Blocks.
Figures
Figures produced by code cells are automatically included in the rendered output. Code cell options provide additional control over how figures are displayed.
For example, update the code cell for the scatter plot by adding a caption with fig-cap
, and improve accessability by adding alternative text with fig-alt
:
#| fig-cap: City and highway mileage for 38 popular models of cars.
#| fig-alt: Scatterplot of city vs. highway mileage for cars, where points are colored by the number of cylinders. The plot displays a positive, linear, and strong relationship between city and highway mileage, and mileage increases as the number of cylinders decreases.
To cross-reference a figure replace the label
with one that that starts with fig-
:
#| label: fig-scatterplot
Then you can update the narrative to refer to the figure using its label:
@fig-scatterplot shows a positive, strong, and linear relationship between the city and highway mileage of these cars.
Preview the document to see the plot now has a caption and an automatically generated number, which is linked from the text.
You can control the size of all the figures in the document by setting fig-width
and fig-height
, expressed in inches, in the document header:
---
title: Quarto Computations
echo: false
fig-height: 3.5
fig-width: 6
---
To override the figure size for individual images, use the fig-width
and fig-height
options as code cell options:
#| label: fig-scatterplot
#| fig-width: 6
#| fig-height: 3.5
ggplot(mpg, aes(x = hwy, y = cty, color = cyl)) +
geom_point(alpha = 0.5, size = 2) +
scale_color_viridis_c() +
theme_bw()
To override the figure size for individual images, specify the plot size in your code. For example, in plotnine
you can use figure_size
argument to theme()
:
(="hwy", y="cty", color="cyl"))
ggplot(mpg, aes(x+ geom_point(alpha=0.5, size=2)
+ scale_color_continuous()
+ theme_bw()
+ theme(figure_size=(6, 3.5))
)
Quarto provides additional flexibility for figures. You can:
Produce figure panels with multiple figures, each with its subcaption. See the article Figure Layout for details.
Allow figures to span the page or screen, or place them in the margin. See the documentation on Article Layout to learn more.
Cell Workflow
You can add a new code cell by running the command Quarto: Insert Code Cell, using the keyboard shortcut , or using the Insert Code Cell button in the editor toolbar.
Since .qmd
documents are plain text, you can also create a new code cell by typing (or copying and pasting) the code cell syntax:
```{r}
```
```{python}
```
Go ahead and add a new code cell to your document after the scatter plot cell.
To get help with code cell options, start by writing the code cell option comment (#|
), then hit to bring up a list of completions. Keep typing to filter the list, or use the arrow keys to navigate. When you find the option you want, hit to insert it into your code cell.
Practice this to add echo: true
to your code cell, and label: nobs
.
Finally, add some code to the cell.
nrow(mpg)
len(mpg)
Preview the document again to see the output of your code cell.
This isn’t a very pretty way to display the number of observations. An alternative is to use inline code, which you’ll cover next.
Code cells using the ```{language}
syntax are sometimes called executable code cells because they will be executed by the computational engine (e.g. knitr
or jupyter
).
If you want to show code without it being processed by the computational engine, use a code block:
```r
# Code goes here
```
```python
# Code goes here
```
You can read more and see some syntax alternatives at Markdown Basics: Source Code.
Inline Code
To include executable expressions within markdown text, enclose the expression in `{r} `
1.
To include executable expressions within markdown, enclose the expression in `{python} `
.
For example, you can use inline code to state the number of observations in our data. Try adding the following markdown text to your Quarto document.
`{r} nrow(mpg)` observations in our data. There are
`{python} len(mpg)` observations in our data. There are
Save your document and preview the rendered output. The expression inside the backticks has been executed and the sentence includes the actual number of observations.
There are 234 observations in our data.
You could now delete the code cell that did the same computation, since the inline code expression has replaced it.
If the expression you want to inline is more complex, involving many functions or a pipeline, we recommend including it in a code cell (with echo: false
) and assigning the result to an object. Then, you can call that object in your inline code.
For additional details on inline code expressions, visit the Inline Code documentation.
Final Document
If you followed along step-by-step with this tutorial, you should now have a Quarto document that implements everything we covered. Otherwise, you can download a completed version of computations.qmd
below.
Next Up
You’ve now covered the basics of customizing the behavior and output of executable code in Quarto documents.
Next, check out the Authoring Tutorial to learn more about output formats and technical writing features like citations, crossrefs, and advanced layout.
Footnotes
Quarto also supports the Knitr syntax
`r `
, read more in Inline Code.↩︎