Reputation: 411
Simple question but can't find a solution. I have a quarto document (but this apply to Markdown as well) in which I use R to execute some code. Obviously, in the first chunk of the document, I load the packages needed (let's say for example):
```{r setup}
library(tidyverse)
library(survival)
library(survminer)
```
Now, everytime I knit the file to render the document, these packages are loaded, which can be pretty time consuming especially if you have a long list of packages to import. using cache=TRUE
doesn't seem to work properly. Is there anyway to avoid loading the package everytime I knit the document, and only load them when they are not loaded in the environment/in the first knit call of the session at least?
Upvotes: 3
Views: 1740
Reputation: 45007
The usual way to run Quarto or RMarkdown is in a clean session, not in the current session. So you normally only have a minimal set of packages already loaded.
If you run rmarkdown::render( ... )
in a session, that doesn't happen, and things will run in the current session. That will speed up library()
calls a lot, because they do nothing if the package has already been attached to the search list.
I don't know if something similar is available for Quarto, but in any case, it's a risky strategy: what you hope for from an RMarkdown or Quarto document is something that is reproducible. If you run in the current session, you run the risk of getting results that depend on variables in the current session.
I'd advise you to identify which packages are slow to load, and try to follow @Arthur's suggestion from a comment: precompute the objects that those packages produce, and just load them in the document. Then you may not need the package at all.
Upvotes: 1