R Markdown supports a variety of languages through the use of knitr language engines. Where users wish to write Stan programs as chunks directly in R Markdown documents there are three options:
Behind the scenes in each option, the engine compiles the model code
in each chunk and creates an object that provides methods to run the
model: a stanmodel
if Rstan is being used, or a
CmdStanModel
in the CmdStanR case. This model object is
assigned to a variable with the name given by the
output.var
chunk option.
This is the default option. In that case we can write, for example:
If CmdStanR is being used a replacement engine needs to be registered along the following lines:
This overrides knitr’s built-in stan
engine so that all
stan
chunks are processed with CmdStanR, not RStan. Of
course, this also means that the variable specified by
output.var
will no longer be a stanmodel
object, but instead a CmdStanModel
object, so the example
code above would look like this:
While the default behavior is to override the built-in
stan
engine because the assumption is that the user is
probably not using both RStan and CmdStanR in the same document or
project, the option to use both exists. When registering CmdStanR’s
knitr engine, set override = FALSE
to register the engine
as a cmdstan
engine:
This will cause stan
chunks to be processed by knitr’s
built-in, RStan-based engine and only use CmdStanR’s knitr engine for
cmdstan
chunks:
Use cache=TRUE
chunk option to avoid re-compiling the
Stan model code every time the R Markdown is knit/rendered.
You can find the Stan model file and the compiled executable in the document’s cache directory.
When running chunks interactively in RStudio (e.g. when using R
Notebooks), it has been observed that the built-in, RStan-based
engine is used for stan
chunks even when CmdStanR’s engine
has been registered in the session as the engine for stan
.
As a workaround, when running chunks interactively, it is
recommended to use the override = FALSE
option and change
stan
chunks to be cmdstan
chunks.
Do not worry: if the template you use supports syntax highlighting
for the Stan language, that syntax highlighting will be applied to
cmdstan
chunks when the document is knit/rendered.