# Best practices for using stan model within a function

**URL:** <https://discourse.mc-stan.org/t/best-practices-for-using-stan-model-within-a-function/15346>\
**Category:** RStan\
**Tags:** rstan, techniques\
**Created:** [May 23, 2020, 3:42pm UTC](https://discourse.mc-stan.org/t/best-practices-for-using-stan-model-within-a-function/15346 "2020-05-23T15:42:29Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ramiro](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/ramiro/32/7587_2.png) [@ramiro](https://discourse.mc-stan.org/u/ramiro)\
**Post date:** [May 23, 2020, 3:42pm UTC](https://discourse.mc-stan.org/t/best-practices-for-using-stan-model-within-a-function/15346/1 "2020-05-23T15:42:29Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![hhau](https://avatars.discourse-cdn.com/v4/letter/h/2bfe46/32.png) [@hhau](https://discourse.mc-stan.org/u/hhau)\
**Post date:** [May 23, 2020, 6:25pm UTC](https://discourse.mc-stan.org/t/best-practices-for-using-stan-model-within-a-function/15346/2 "2020-05-23T18:25:03Z")

</div>

Are you using [rstantools](https://github.com/stan-dev/rstantools)? The [guide](https://mc-stan.org/rstantools/articles/minimal-rstan-package.html) is very useful, and the package is intended to help you avoid the exact issue you are encountering :).

---

<div class="post-metadata">

**Author:** ![ramiro](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/ramiro/32/7587_2.png) [@ramiro](https://discourse.mc-stan.org/u/ramiro)\
**Post date:** [May 23, 2020, 9:02pm UTC](https://discourse.mc-stan.org/t/best-practices-for-using-stan-model-within-a-function/15346/3 "2020-05-23T21:02:42Z")

</div>

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.
