Saving stanfit object

Current my code in R is:

fit1 <- stan(model_code=M, data=dat,chains=1,init=list(list(mu=0.001,r=0.001)),iter=20000,thin=5)

I’m using package “ggmcmc” to create trace, autocorrelation plots, etc:

S=ggs(fit1)

ggs_traceplot(S)

How should I save the stanfit object fit1, so I can do the plots later without calling the stan function and rerunning the model?

1 Like

In R you can use saveRDS(fit1, "fit1.rds").

This saves the rds file in you working directory. You can read it using fit1 <- readRDS("fit1.rds") (make sure you are in the correct working directory).

I don’t know if this is the correct or official way (if there is one) to do it, though.

2 Likes

That works. Thank you!

A few suggestions if these are the settings you are using when fitting your model:

  • Always run many chains (the default is 4).
  • I rarely find an example were Stan requires 20000 iterations. I would start with the default (2000 per chain, of which 1000 are warmup) and only increase if necessary. Numbers like 20000 are common when using other MCMC algorithms but that’s usually overkill for HMC/NUTS.
  • Thinning is never a good idea unless your posterior draws take up too much memory. It’s a standard practice because with other MCMC algorithms you often need to run very long chains, but it’s really just throwing away information.

ggmcmc is a nice package. In case you’re interested also we have our own package for plotting (also based on ggplot2) called bayesplot (Plotting for Bayesian Models • bayesplot).

Using saveRDS like @Max_Mantei suggested is a good option.

1 Like