Stan recompile to avoid R from crashing


Good morning all,

I encounter a problem with respect to the usage of the stan function (package rstan on R).
Whenever I compile this line in an R script:
fit <- stan(model_code = model, data = data,warmup = 100,iter = 300, chains = 1)
With the variable model and data well defined, I can compile it as many times as I want withtout the fitting of the model to happen again.
Yet, whenever I call this very same line inside another function, each time I will run it, R will return me this message
recompiling to avoid crashing R session
Which means that the fitting will be computed again regardless of previous compilation. This takes a lot of time and I would love to avoid having to wait for this.

R version 3.3.2 (2016-10-31)
rstan version '2.16.2'

Could you please help me on this?
Thanks a lot for your help


It does not re-use Stan models within local function scope because the model could get garbage collected and crash your R session. To avoid this, you need to call stan_model once in the global environment to compile the model and then call sampling within your local function. It will find the compiled model with lexical scoping.


Thanks a lot for the rapid and good feedback!