9  Other topics

9.1 Too much or too slow code

If code runs slowly, the output of code blocks can be cached, so next time the document is rendered the existing cached results can be used, unless the code has been changed. The caching system in quarto can be activated by setting the code block option cache = TRUE. The caching system can be tricky to set up for complex projects, and the targets package is a much more robust framework for building reproducible analysis pipelines. See this demonstration project for an example of how to set up targets.

If there is simply too much code, you can move code into another file. There are two ways to do this. The first is with includes. These effectively copy and paste text and code from another quarto file. To include the file “_load-data.qmd”, which has a code block for loading the data, we need this shortcode.

{{< include _load-data.qmd >}}

The shortcode needs to be on its own line, with space above and below. The file name should start with an underscore. Includes could also be useful for different sections of a manuscript

The second method is to use the file option in a code block. For example, to run the code from the file “load-data.R”, we could use the following code block.

#| label: load-data
#| file: load-data.R

Or if we need to use here, we can use this one.

#| label: load-data
#| file: !expr here::here("load-data.R")

9.2 Paramertised reports

If you need a template for many reports, for example, showing results for a specific location or time period, consider using Paramertised reports which allow you to pass a variable into an quarto document when it is rendered.

This is done by declaring one or more parameters in the YAML. For example, to make a report about just one of the species in the penguins dataset, we might use this YAML, which sets the default value of species to Adelie.

title: "Penguin Report"
  species: Adelie

We can now access this parameter with param$species. Perhaps in a chunk like this

palmerpenguins::penguins |> 
  filter(species == params$species) |> 
  summarise(mean_bill_length = mean(bill_length_mm, na.rm = TRUE))

If we wanted to make the report for a different species, we would have to run quarto_render in the console.

    input = "penguin_report.qmd", 
    execute_params = list(species = "Gentoo")