Reuse Quarto Chunks
I have recently learned a very nice trick with Quarto to reuse a chunk content without writing again. This is very useful for teaching and for slides where the available space is limited. As use case let’s assume you are creating a two-columns slide and you want to show the code on the left and the result on the right.
Usually you can do something like this:
On the left
#| label: chunk-example
#| eval: false
#| echo: true
|>
iris ggplot(aes(x = Sepal.Length,
y = Petal.Width,
color = Species)) +
geom_point()
On the right1
#| eval: true
#| echo: false
|>
iris ggplot(aes(x = Sepal.Length,
y = Petal.Width,
color = Species)) +
geom_point()
The key difference is that on the left the code is showed but not evaluated, while on the right the code is evaluated without including the source on the rendered document.
But there is a more compact and efficient way to achieve the same result:
On the left
#| label: chunk-example
#| eval: false
#| echo: true
|>
iris ggplot(aes(x = Sepal.Length,
y = Petal.Width,
color = Species)) +
geom_point()
On the right
#| label: chunk-example
#| echo: false
Using the same code label will result in reusing the same code. In addition, any changes in the source code will be reflected in the other chunk(s). With this trick, the same code can be reused multiple times across the entire document.
Footnotes
Clearly the code here is not evaluated, in the rendered document the plot will be showed instead of the code.↩︎