# Running a Stan model many times in a for loop

**URL:** <https://discourse.mc-stan.org/t/running-a-stan-model-many-times-in-a-for-loop/37222>\
**Category:** Modeling\
**Created:** [November 11, 2024, 8:28pm UTC](https://discourse.mc-stan.org/t/running-a-stan-model-many-times-in-a-for-loop/37222 "2024-11-11T20:28:05Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![jonah](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/jonah/32/200_2.png) [@jonah](https://discourse.mc-stan.org/u/jonah)\
**Post date:** [November 11, 2024, 11:07pm UTC](https://discourse.mc-stan.org/t/running-a-stan-model-many-times-in-a-for-loop/37222/3 "2024-11-11T23:07:13Z")

</div>

@Bob_Carpenter is right that there aren’t any RDS files saved by default. Is it possible you’re referring to something else?

If you’re going to run many times in a loop I would lean towards using CmdStanR. It’s doable with RStan but it’s possible that keeping everything in memory in R is causing the issue (could be something else entirely though). CmdStanR will save (temporary, unless otherwise specified) CSV files each time you run it, but it won’t read them into memory in R until you use a method that requires them.

If you definitely want to use RStan I recommend not using the `stan()` function for this and instead using `stan_model()` to compile the model and then `sampling()` to run MCMC repeatedly with different datasets. Something like this:

```r
model <- stan_model(file)
fits <- list()
for (n in 1:seq_along(datasets)) {
  fits[[n]] <- sampling(model, data = datasets[[n]]) 
}

```

Although perhaps you’re already doing that. If the issue is running out of space when using RStan you could try [Looping over many fits fills hard drive - #4 by sweenejo](https://discourse.mc-stan.org/t/looping-over-many-fits-fills-hard-drive/5523/4).

And, like @Bob_Carpenter said, it could be that in this particular case the issue isn’t the looping but that you’re running into some other issue, e.g. with specific seeds.

---

_[View the full topic](https://discourse.mc-stan.org/t/running-a-stan-model-many-times-in-a-for-loop/37222)._
