Best practices for using stan model within a function

I am developing an R package that uses stan. This involves calling functions that run stan within them.

As an example I have a function that generates fake data from a model using the stan “sampling” function, i.e.:

generateFakeData <- function(N,alpha,beta) {
   compiledStanModel <- stan_model("myStanModel.stan") 
   simulatedData <- sampling(
     data = list(N = N,
                 alpha = alpha,

This runs into problems as when I am calling the function with tests, etc. the stan model gets recompiled and at best I get a “recompiling to avoid crashing R session” message. At worst RStudio crashes.

I can just pass the compiledStanModel as a function parameter, but what is the best practice? Especially if this will eventually become a package. Should the model be a global variable somewhere?

Thank you in advance.

Are you using rstantools? The guide is very useful, and the package is intended to help you avoid the exact issue you are encountering :).


Thank you very much @hhau, I actually did use rstantools to setup the package but did not read carefully enough on the other aspects of the package. Thank you.