Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork271
RStan Getting Started
RStan is theR interface to Stan. For more information on Stan and its modeling language visit the Stan website athttp://mc-stan.org/
To install the latest development version of RStan use
# run the next line if you already have rstan installed# remove.packages(c("StanHeaders", "rstan"))install.packages("rstan",repos= c('https://stan-dev.r-universe.dev', getOption("repos")))
This version is not yet officially released, but it provides access to a more recent version of the Stan language than the latest official RStan release. See the Configuring C++ Toolchain and Verifying Installation sections below to make sure you have the necessary setup for compiling Stan programs (you can ignore the Installing RStan section below).
Using R version 4.2.0 or later is strongly recommended. If necessary, you can install the latest version of R fromhere.
In addition, we strongly recommend that you useRStudio version 1.4.x or later because it has great support for Stan.
Prior to installing RStan, you need to configure your R installation to be able to compile C++ code. Follow the link below for your respective operating system for more instructions:
To be on the safe side, it is sometimes necessary to remove any existing RStan via
remove.packages("rstan")if (file.exists(".RData")) file.remove(".RData")
Then, restart R.
If you are using R version 3.x on a Mac, go tohere. Otherwise, you can usually simply type (exactly like this)
Sys.setenv(DOWNLOAD_STATIC_LIBV8=1)# only necessary for Linux without the nodejs library / headersinstall.packages("rstan",repos="https://cloud.r-project.org/",dependencies=TRUE)
To verify your installation, you can run the RStan example/test model:
example(stan_model,package="rstan",run.dontrun=TRUE)
The model should then compile and sample. You may also see the warning:
The rest of this document assumes that you have already installed RStan by following the instructions above.
The package name isrstan (all lowercase), so we start by executing
library("rstan")# observe startup messages
As the startup message says, if you are usingrstan locally on a multicore machineand have plenty of RAM to estimate your model in parallel, at this point execute
options(mc.cores=parallel::detectCores())
In addition, you should follow the second startup message that says to execute
rstan_options(auto_write=TRUE)
which allows you to automatically save a bare version of a compiled Stan program to the hard disk so that it does not need to be recompiled (unless you change it). You will need to run these commands each time you load therstan library.
Finally, if you use Windows, there will be a third startup message saying not to use--march=native compiler flag. You can ignore this warning if you followed the steps above and yourMakevars.win file does not contain this flag.
This is an example in Section 5.5 of Gelmanet al (2003), which studiedcoaching effects from eight schools. For simplicity, we call this example"eight schools."
We start by writing a Stan program for the model in a text file. If you are using RStudio version 1.2.x or greater, click on File -> New File -> Stan File . Otherwise, open your favorite text editor. Either way, paste in the following and save your work to a file calledschools.stan in R's working directory (which can be seen by executinggetwd())
// saved as schools.standata {int<lower=0> J;// number of schoolsarray[J]real y;// estimated treatment effectsarray[J]real<lower=0> sigma;// standard error of effect estimates}parameters {real mu;// population treatment effectreal<lower=0> tau;// standard deviation in treatment effectsvector[J] eta;// unscaled deviation from mu by school}transformed parameters {vector[J] theta= mu+ tau* eta;// school treatment effects}model {target+=normal_lpdf(eta |0,1);// prior log-densitytarget+=normal_lpdf(y | theta, sigma);// log-likelihood}
Be sure that your Stan programs ends in a blank line without any characters including spaces and comments.
In this Stan program, we lettheta be a transformation ofmu,eta, andtauinstead of declaringtheta in theparameters block, which allows the sampler will run more efficiently (see detailed explanation). We can prepare the data (which typically is a named list) in R with:
schools_dat<-list(J=8,y= c(28,8,-3,7,-1,1,18,12),sigma= c(15,10,16,11,9,11,10,18))
And we can get a fit with the following R command. Note that the argument tofile = should point to where the file is on your file system unless you have put it in the working directory of R in which case the below will work.
fit<- stan(file='schools.stan',data=schools_dat)
The objectfit, returned from functionstan is anS4 object of classstanfit. Methods such asprint,plot, andpairs are associated with thefitted result so we can use the following code to check out the results infit.print provides a summary for the parameter of the model as wellas the log-posterior with namelp__ (see the following example output).For more methods and details of classstanfit, see the help of classstanfit.
In particular, we can use theextract function onstanfit objects toobtain the samples.extract extracts samples from the stanfitobject as a list of arrays for parameters of interest, or just an array.In addition, S3 functionsas.array,as.matrix, andas.data.frame are definedforstanfit objects (usinghelp("as.array.stanfit") to checkout the help document in R).
print(fit)plot(fit)pairs(fit,pars= c("mu","tau","lp__"))la<- extract(fit,permuted=TRUE)# return a list of arraysmu<-la$mu### return an array of three dimensions: iterations, chains, parametersa<- extract(fit,permuted=FALSE)### use S3 functions on stanfit objectsa2<- as.array(fit)m<- as.matrix(fit)d<- as.data.frame(fit)
The Rats example is also a popular example. For example, we can find theOpenBUGS version fromhere, which originally is fromGelfandet al (1990).The data are about the growth of 30 rats weekly for five weeks.In the following table, we list the data, in which we usex to denote the datesthe data were collected. We can try this example using the linked datarats.txtand model coderats.stan.
| Rat | x=8 | x=15 | x=22 | x=29 | x=36 | Rat | x=8 | x=15 | x=22 | x=29 | x=36 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 151 | 199 | 246 | 283 | 320 | 16 | 160 | 207 | 248 | 288 | 324 | |
| 2 | 145 | 199 | 249 | 293 | 354 | 17 | 142 | 187 | 234 | 280 | 316 | |
| 3 | 147 | 214 | 263 | 312 | 328 | 18 | 156 | 203 | 243 | 283 | 317 | |
| 4 | 155 | 200 | 237 | 272 | 297 | 19 | 157 | 212 | 259 | 307 | 336 | |
| 5 | 135 | 188 | 230 | 280 | 323 | 20 | 152 | 203 | 246 | 286 | 321 | |
| 6 | 159 | 210 | 252 | 298 | 331 | 21 | 154 | 205 | 253 | 298 | 334 | |
| 7 | 141 | 189 | 231 | 275 | 305 | 22 | 139 | 190 | 225 | 267 | 302 | |
| 8 | 159 | 201 | 248 | 297 | 338 | 23 | 146 | 191 | 229 | 272 | 302 | |
| 9 | 177 | 236 | 285 | 350 | 376 | 24 | 157 | 211 | 250 | 285 | 323 | |
| 10 | 134 | 182 | 220 | 260 | 296 | 25 | 132 | 185 | 237 | 286 | 331 | |
| 11 | 160 | 208 | 261 | 313 | 352 | 26 | 160 | 207 | 257 | 303 | 345 | |
| 12 | 143 | 188 | 220 | 273 | 314 | 27 | 169 | 216 | 261 | 295 | 333 | |
| 13 | 154 | 200 | 244 | 289 | 325 | 28 | 157 | 205 | 248 | 289 | 316 | |
| 14 | 171 | 221 | 270 | 326 | 358 | 29 | 137 | 180 | 219 | 258 | 291 | |
| 15 | 163 | 216 | 242 | 281 | 312 | 30 | 153 | 200 | 244 | 286 | 324 |
y<- as.matrix(read.table('https://raw.github.com/wiki/stan-dev/rstan/rats.txt',header=TRUE))x<- c(8,15,22,29,36)xbar<- mean(x)N<- nrow(y)T<- ncol(y)rats_fit<- stan(file='https://raw.githubusercontent.com/stan-dev/example-models/master/bugs_examples/vol1/rats/rats.stan',data=list(N=N,T=T,y=y,x=x,xbar=xbar))
You can run many of the BUGS examples and some others that we have created in Stan by executing
model<- stan_demo()
and choosing an example model from the list that pops up. The first time you callstan_demo(), it will ask you if you want to download these examples. You should choose option 1 to put them in the directory whererstan was installed so that they can be used in the future without redownloading them. Themodel object above is an instance of classstanfit, so you can callprint,plot,pairs,extract, etc. on it afterward.
More details about RStan can be found in the documentation including the vignette of packagerstan.For example, usinghelp(stan) andhelp("stanfit-class") to check out the help for functionstanand S4 classstanfit.
And seeStan's modeling language manual for details about Stan's samplers, optimizers, and the Stan modeling language.
In addition, theStan User's Mailing listcan be used to discuss the use of Stan, post examples or ask questions about (R)Stan. When help is needed,it is important to provide enough information such as the following:
- properly formatted syntax in the Stan modeling language
- data
- necessary R code
- dump of error message using
verbose=TRUEandcores=1when calling thestanorsamplingfunctions - information about R by using function
sessionInfo()in R
- Gelman, A., Carlin, J. B., Stern, H. S., and Rubin, D. B. (2003).Bayesian Data Analysis, CRC Press, London, 2nd Edition.
- Stan Development Team.Stan Modeling Language User's Guide and Reference Manual.
- Gelfand, A. E., Hills S. E., Racine-Poon, A., and Smith A. F. M. (1990). "Illustration of Bayesian Inference in Normal Data Models Using Gibbs Sampling", Journal of the American Statistical Association, 85, 972-985.
- Stan
- R
- BUGS
- OpenBUGS
- JAGS
- Rcpp