pre-render an R script for each chapter of a quarto book project
Asked Answered
N

1

13

I have a bookdown project in R and like to switch to Quarto. In the bookdown project I have an R script _common.R (it includes libraries and various settings and helper functions) to run before the rendering of each chapter (separate qmd file).

How can I implement such a script-file in Quarto?

I tried to set in _quarto.yml:

project:
  type: book
  pre-render: _common.R

But this will only run the script once before the rendering of the complete book, not before each chapter. Each chapter seems to be rendered in its own environment so all the settings and scripts from _common.R are not available.

A workaround is to include

```{r echo = FALSE, message=FALSE, warning=FALSE}
source("_common.R")
```

at the top of each .Rmd/.qmd file. Is there a better solution?

Any help appreciated!

Nonmetallic answered 29/8, 2022 at 15:23 Comment(0)
H
5

As an alternative to your proposed workaround, you can use a project-specific .Rprofile file in your project and call the source inside that .Rprofile.

.Rprofile

source("_common.R")

And in this approach, you don't have to source the _common.R file at the start of each chapter qmd files.

Hashish answered 30/8, 2022 at 0:48 Comment(2)
Keep in mind that R will source only one .Rprofile file, so you need either explicitly source the user-level .Rprofile at the top of your project-level .Rprofile with source("~/.Rprofile") or you will lose your project-level .Rprofile settings.Karol
Instead of using a {knitr} chunk with source("_common.R") using the include shortcode {{< include _common.qmd >}} would be a more general Quarto like solution, not restricted to R. See Includes and source() script at start of document. But this still has the disadvantage, that you need to paste this include statement inside all your qmd-files.Karol

© 2022 - 2024 — McMap. All rights reserved.