Mark
Mark

Reputation: 200

knitr fails on Stan chunk with cache=TRUE

According to this Github issue (marked as fixed for knitr v1.12), it should be possible to cache Stan chunks in knitr so that the Stan model object doesn't need to be re-compiled every time we knit the file.

However, using knitr v1.20 (R v3.5.1 within RStudio v1.1.463), when knitting the file for the second time (so that the cache has already been built), I get an error:

Quitting from lines 9-18 (Testing_Stan_cache.Rmd) 
Error in fun(environment()) : invalid first argument
Calls: <Anonymous> ... call_block -> <Anonymous> -> lazyLoad -> lazyLoadDBexec -> fun
Execution halted

Example Rmarkdown file (lines 9-18 mentioned in the error are the Stan chunk):

---
title: "Testing Stan cache"
output: html_document
---

## Stan model

```{stan output.var="ex1", cache=TRUE}
data {
  int<lower=0, upper=1> X[100];
}
parameters {
  real<lower=0, upper=1> p;
}
model {
  X ~ bernoulli(p);
}
```

## Run the model 

```{r}
library(rstan)
fit <- sampling(ex1, data=list(X = rbinom(100, 1, 0.3)))
print(fit)
```

I've also tried it with cache.lazy=FALSE in the Stan chunk options, but get a different error:

Quitting from lines 23-26 (Testing_Stan_cache.Rmd) 
Error in sampling(ex1, data = list(X = rbinom(100, 1, 0.3))) : 
  object 'ex1' not found
Calls: <Anonymous> ... withCallingHandlers -> withVisible -> eval -> eval -> sampling
Execution halted

Upvotes: 4

Views: 617

Answers (1)

Yihui Xie
Yihui Xie

Reputation: 30164

This is a bug of knitr, which I just fixed on Github. Please try the current development version:

remotes::install_github('yihui/knitr')

Upvotes: 1

Related Questions