Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

RStan Getting Started

Andrew Johnson edited this pageJun 3, 2024 ·161 revisions

RStan is theR interface to Stan. For more information on Stan and its modeling language visit the Stan website athttp://mc-stan.org/

Latest Development Version:2.35.x (unreleased)

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).

Latest Released Version:2.26.3   (September 2023)

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.

Configuring C++ Toolchain

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:

Installing RStan

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)

Verifying Installation

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:

How to Use RStan

The rest of this document assumes that you have already installed RStan by following the instructions above.

Loading the package

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.

Example 1: Eight Schools

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)

Example 2: Rats

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.

Ratx=8x=15x=22x=29x=36Ratx=8x=15x=22x=29x=36
115119924628332016160207248288324
214519924929335417142187234280316
314721426331232818156203243283317
415520023727229719157212259307336
513518823028032320152203246286321
615921025229833121154205253298334
714118923127530522139190225267302
815920124829733823146191229272302
917723628535037624157211250285323
1013418222026029625132185237286331
1116020826131335226160207257303345
1214318822027331427169216261295333
1315420024428932528157205248289316
1417122127032635829137180219258291
1516321624228131230153200244286324
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))

Example 3: Anything

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 Help

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 usingverbose=TRUE andcores=1 when calling thestan orsampling functions
  • information about R by using functionsessionInfo() in R

References

  • 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

Clone this wiki locally


[8]ページ先頭

©2009-2025 Movatter.jp