Search code examples
ryamlrstudioquarto

Passing data from one qmd file to another in a Quarto book template?


Could I ask advice for best practice on passing data from one quarto file to another in the RStudio Quarto book template?

The default book template looks like this (_quarto.yml)

project:
  type: book

book:
  title: "TestTest"
  author: "Jane Doe"
  date: "08/06/2022"
  chapters:
    - index.qmd
    - intro.qmd
    - summary.qmd
    - references.qmd

bibliography: references.bib

format:
  html:
    theme: cosmo
  pdf:
    documentclass: scrreprt

editor: visual

I put my code and text into the files e.g. index.qmd and intro.qmd. My question is: it appears that the files are independent of each other. If I read in data from a DB into index.qmd then intro.qmd is ignorant of it. So how is it best to pass data from one to the other? I'm loathe to query the database for the same set of data in each of my qmd files.

Any help would be much appreciated. Phil,


Solution

  • I think quarto files should be independent to make the results predictable and reproducible. If you want to avoid rerunning the same code multiple times, you can use caching. There is the R package memoise to cache the results of a function call e.g. on the hard disk. If the function is called again with the same arguments, the result will be loaded from the cache instead of querying the database twice. There is also the R package targets to cache results of R code. Here, the code is structured as a DAG (tree) of steps, which depend on their precursors. Use this kind of caching if you have a more complex workflow.