A comment on this previous question: Include Stan code.
If you want to include a Stan model in an RMarkdown/Quarto document - and you want to have syntax highlighting - you can put the Stan model in a Stan code chunk and the R code to run it in a different chunk. Using output.var =
chunk option for the Stan code chunk allows you to refer to the model in the R chunk.
```{stan output.var = "compiled_model"}
data {
}
parameters {
}
model {
}
```
When the document is executed the model will be compiled and stored in the variable compiled_model
, you can then sample from the model in a later chunk using the following chunk. Because the model is precompiled you call sampling
not stan
.
```{r}
# R code to build the data_list goes here
fit1 <- sampling(
compiled_model, # Stan program object from previous chunk
data = data_list, # named list of data
chains = 4, # number of Markov chains
warmup = 1000, # number of warmup iterations per chain
iter = 2000, # total number of iterations per chain
cores = 4, # number of cores (could use one per chain)
refresh = 100, # progress shown
verbose = FALSE # TRUE gives more logging
)
```