Saving and sharing an rstan model fit

This might be a basic question, but a search on relevant terms did not reveal a discussion. Apologies if I missed anything.

I have estimated a model with rstan, and I would like to save the model fit object to send to a colleague, who wishes to extract posterior samples, calculate WAIC, etc. Formerly, I have saved model fits as an R object (*.robj) file. When I try that with a Stan model, however, attempts to load it into a new R workspace result in an error (“error reading from connection”). It occurs to me that rstan models might be tied to their C++ compiler somehow . . .

How is it possible to save and share rstan fit objects?


You first have to kill the Dynamic Shared Object inside the stanmodel slot of a stanfit object. Like

fit@stanmodel@dso <- new("cxxdso")
saveRDS(fit, file = "fit.rds")

Of course, only do that when you are done with it because you would have to recompile to estimate with it further.


That seems straightforward enough, but I just tried it and hit a snag.

That is, when I try to load the saved model, I get an error:

fit@stanmodel@dso <- new("cxxdso")
saveRDS(fit, file = "fit.rds")

Error: bad restore file magic number (file may be corrupted) – no data loaded
In addition: Warning message:
file 'fit.rds’ has magic number ‘X’
** Use of save versions prior to 2 is deprecated**

1 Like

Sorry, I should have looked a little closer. Reading in the models with readRDS seemingly took care of it.

fit <- readRDS("fit.rds")

Thanks, Ben.


Can I get a checkmark on my previous post so that it bubbles up to the top of the thread for future reference?