RMarkdown and stan code printing via get_stancode()?

In RMarkdown I have a stanfit object and I print the code as recommended here:

```{r code_1, eval = TRUE}
cat(get_stancode(stan_fit))

But this isn’t so pretty:

Is there any way to render this with the nice color formatting we get with a stan code chunk like this:

```{stan, output.var="ex1"}
parameters {
  real y[2]; // test what comments look like
}
model {
  y[1] ~ normal(0, 1);
  y[2] ~ double_exponential(0, 2);
}

Which is pretty:

Thank you !!

here’s a hack that seems to work - put your code into a file, read it into a variable.
file foo.stan contains your example code.

then your chunk header is:

{stan, output.var="ex1", code=readLines('foo.stan')}

and the body is empty

this chunk will take a while to render - not sure why.

2 Likes

I recently wanted my Stan code highlighted with color and found https://github.com/vsbuffalo/stanhl. The issue is that it doesn’t work with windows. But I got it to work. See https://github.com/vsbuffalo/stanhl/issues/4.

Now the output of my html Rmarkdown doc is:

> ---
> title: "test"
> output: html_document
> ---
> 
> ```{r setup, include=FALSE}
> knitr::opts_chunk$set(echo = TRUE)
> ```
> 
> ## Test
> 
> ```{r,echo=FALSE,results='asis'}
> library(stanhl)
> stanhl_html()
> ```
> 
> ```{r,echo=FALSE,results='asis'}
> m <- "
> data {
>   int<lower=0> N;
>   vector[N] weight;
>   vector[N] diam1;
>   vector[N] diam2;
>   vector[N] canopy_height;
> }
> transformed data {
>   vector[N] log_weight;
>   vector[N] log_canopy_volume;
>   log_weight        <- log(weight);
>   log_canopy_volume <- log(diam1 .* diam2 .* canopy_height);
> }
> parameters {
>   vector[2] beta;
>   real<lower=0> sigma;
> }
> model {
>   log_weight ~ normal(beta[1] + beta[2] * log_canopy_volume, sigma);
> }
> "
> stanhl(m)
2 Likes

woo hoo ! Since I only have the stanfit object, not the stan code file itself, this combination with your suggestions works:

```{r code_1, eval = TRUE, echo = FALSE}
cat(get_stancode(stan_fit_1), file = "code1.stan")
/```

```{stan, output.var="ex1", code=readLines('code1.stan')}
/```
2 Likes

It’s compiling the Stan model in the background and storing it in the “ex1” variable. You could probably use cmdstanr as a knitr engine instead of rstan and it would speed it up a bit.

1 Like