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(
compiledStanModel,
data = list(N = N,
alpha = alpha,
...etc
}
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.