Written and maintained by CASRAI Editorial Board
Published · Last updated
On this page
rstan is the R interface to Stan, the probabilistic programming language: you write a statistical model in a Stan program, and the rstan package parses, compiles and fits it from R, returning full Bayesian inference by Markov chain Monte Carlo (MCMC), approximate inference by variational methods, or (optionally penalized) maximum likelihood by optimization. It is distributed on CRAN, and the sections below take you from the C++ toolchain through installation, a complete eight-schools fit, and a reading of the output against the Stan team’s own diagnostic thresholds.
What rstan is used for in research
The CRAN description of the package reads: an R interface to the header-only Stan library, provided through StanHeaders, that parses, compiles, tests, estimates and analyzes Stan models. In practice researchers use it when a model is not available in a point-and-click package: hierarchical (multilevel) models, models with custom likelihoods, and models where the analyst wants an explicit prior on every parameter. If you are new to the ideas, read the comparison of prior versus posterior distributions first; the choice of priors is covered in prior distributions.
Many people use rstan without writing Stan code. According to the CRAN package page, more than 200 packages import rstan, including brms and rstanarm, so any model you fit through those packages is being sampled by rstan underneath. The same page lists shinystan, bayesplot and rstantools as suggested companion packages for exploring fits and building packages around Stan programs.
A note on the name: “Stan” here is the probabilistic programming language and its inference engine, not an unrelated product or person; “RStan” always means the R interface. The package is licensed GPL (>= 3) and its maintainer on CRAN is Ben Goodrich. Questions go to the Stan forum at discourse.mc-stan.org and bug reports to the package’s GitHub issue tracker.
Install or access rstan
Step 1: install a C++ toolchain
Because rstan compiles each Stan model to C++, the official RStan Getting Started page says to set up a C++ toolchain before installing the package, and it has separate toolchain pages for Windows, macOS and Linux. The CRAN page lists GNU make and pandoc as system requirements and states that rstan depends on R 3.4.0 or later and StanHeaders 2.32.0 or later; the Getting Started page recommends R 4.2.0 or newer.
Step 2: install the package
The documented command is:
install.packages("rstan", repos = "https://cloud.r-project.org/", dependencies = TRUE)
The Getting Started page adds one platform note: on Linux without the nodejs library and headers, run Sys.setenv(DOWNLOAD_STATIC_LIBV8 = 1) before the install command. The page also documents a development version from the Stan team’s r-universe repository, install.packages("rstan", repos = c('https://stan-dev.r-universe.dev', getOption("repos"))), which tracks a newer Stan language than the CRAN release. For reproducible research, record which of the two you used.
Step 3: verify the installation
Run the example attached to stan_model:
example(stan_model, package = "rstan", run.dontrun = TRUE)
If a compile and sampling run completes, the toolchain works. If you must start again, the Getting Started page gives a clean reinstall sequence: remove.packages("rstan"), delete a stray .RData file in the working directory if one exists, and restart R before reinstalling.
Step 4: set the recommended session options
The same page recommends two settings, re-run after each library(rstan): options(mc.cores = parallel::detectCores()) to run chains in parallel (when you have plenty of memory), and rstan_options(auto_write = TRUE) to save a compiled model so an unchanged Stan program is not recompiled.
Step-by-step: fit the eight-schools model
The RStan vignette fits the classic eight-schools hierarchical model, in which each of eight schools has an estimated treatment effect with a known standard error. The steps below follow that vignette (the version published on mc-stan.org/rstan, read 2026-11-14).
- Write the Stan program. Save the following as
schools.stan. The vignette uses the non-centered parameterization, in which a standardized vectoretais rescaled into the school effectstheta:data { int<lower=0> J; // number of schools array[J] real y; // estimated treatment effects array[J] real<lower=0> sigma; // s.e. of effect estimates } parameters { real mu; real<lower=0> tau; vector[J] eta; } transformed parameters { vector[J] theta; theta = mu + tau * eta; } model { target += normal_lpdf(eta | 0, 1); target += normal_lpdf(y | theta, sigma); }End the file with a blank line; the Getting Started page notes that a Stan file must end with one.
- Prepare the data as a named list whose names match the
datablock:schools_data <- list( J = 8, y = c(28, 8, -3, 7, -1, 1, 18, 12), sigma = c(15, 10, 16, 11, 9, 11, 10, 18) ) - Compile and sample with
stan():library(rstan) fit1 <- stan( file = "schools.stan", data = schools_data, chains = 4, warmup = 1000, iter = 2000, cores = 1, refresh = 0 )This runs four chains of 2,000 iterations each, discarding the first 1,000 as warmup, with no progress output. The object returned is a
stanfit. - Print and plot the fit with the vignette’s calls:
print(fit1, pars=c("theta", "mu", "tau", "lp__"), probs=c(.1,.5,.9)),plot(fit1),traceplot(fit1, pars = c("mu", "tau"), inc_warmup = TRUE, nrow = 2)andpairs(fit1, pars = c("mu", "tau", "lp__"), las = 1).
The same steps can be applied to your own model by replacing the Stan program and the data list; the structure (a Stan file, a named data list, one stan() call, then diagnostics before interpretation) does not change. A fit of this kind is the building block for the multilevel regressions described in Bayesian regression.
Output and how to read it
The print summary
The vignette’s printed summary for this fit reports, for each parameter, the mean, se_mean (the Monte Carlo standard error of the mean), the standard deviation sd, the requested quantiles, n_eff and Rhat. In that run the population mean mu had a posterior mean of 8.10 (sd 5.06) and the between-school spread tau a posterior mean of 6.29 (sd 5.37), with Rhat equal to 1 for every parameter shown. The vignette defines n_eff as a crude measure of effective sample size and Rhat as the potential scale reduction factor on split chains, which equals 1 at convergence. The row lp__ is the unnormalized log posterior. Summaries use post-warmup draws only, so with four chains of 1,000 post-warmup iterations the fit above has 4,000 draws in total.
Your own numbers will differ slightly from these, because the printed output depends on the random seed and run; the point of the example is the layout. The posterior intervals in the table are the quantities you report, and the diagnostics beside them decide whether you are allowed to report them.
The plots
According to the vignette, plot(fit1) shows 80% inner and 95% outer intervals for the first ten parameters by default. traceplot with inc_warmup = TRUE shows the chains including the warmup phase, so you can see them settle into the same region. pairs draws divergent transitions as red points. The sampler details are available through get_sampler_params, which returns accept_stat__, stepsize__, treedepth__, n_leapfrog__, divergent__ and energy__.
Which diagnostic thresholds to apply
The Stan team’s diagnostics guide (mc-stan.org/learn-stan/diagnostics-warnings.html) states specific rules, collected in the data table below with the rstan column each one corresponds to. In brief: it recommends a final-result R-hat below 1.01 (below 1.1 is often enough for early exploration) and at least four chains; a bulk effective sample size above 100 times the number of chains, which is 400 for four chains, for a final result (above 20 is enough early on); divergent transitions after warmup are not to be safely ignored; and the energy diagnostic E-BFMI should not fall below a nominal threshold of 0.3. It treats hitting the maximum tree depth as an efficiency problem, not a validity problem: if it is the only warning and the effective sample sizes and R-hat are good, it is likely safe to ignore. The reporting question for a methods section is addressed in the Bayesian versus frequentist comparison.
Troubleshooting
The package will not install or compile
Start with the toolchain: the Getting Started page makes it the first step and gives a page per operating system. If an installed package behaves badly after an upgrade, use the clean reinstall sequence in Step 3 above. Also make sure the Stan file ends with a blank line, as the Getting Started page requires.
Divergent transitions after warmup
The diagnostics guide says divergences after warmup cannot be safely ignored. Its recommended order is to reparametrize the model (the non-centered form used above is an example) or use stronger priors; raising adapt_delta is a last resort, and pushing it above 0.99 is, in the guide’s words, seldom useful. The vignette shows the mechanism, control = list(adapt_delta = 0.9) in the stan() call, and notes that the default is 0.8.
Maximum treedepth warnings
The default maximum tree depth is 10. The vignette says to raise max_treedepth if the limit is hit, but the diagnostics guide cautions that values above 12 are seldom useful and that this warning concerns efficiency, so check effective sample size and R-hat first.
Low effective sample size or high R-hat
The guide’s targets are at least four chains, an R-hat below 1.01 and a bulk effective sample size above 400 with four chains for a final result; the looser early-stage targets (R-hat below 1.1, effective sample size above 20) are for exploration only.
Getting help
The Getting Started page asks forum posters to include the Stan code, the data, the R code, the output of the call with verbose = TRUE and cores = 1, and sessionInfo(). A question with those five items can be reproduced by someone else.
Free alternatives and related interfaces
rstan is not the only way to run Stan from a scripting language, and several packages sit on top of it. The table below states only what the official CRAN and CmdStanR pages say.
| Option | What the official page says | Relationship to rstan |
|---|---|---|
| CmdStanR | A lightweight interface to Stan for R users; it only calls compiled executables and does not interface with C++ directly. Install with install.packages("cmdstanr", repos = c('https://stan-dev.r-universe.dev', getOption("repos"))), then install_cmdstan(). Code is BSD 3-clause; documentation is CC-BY 4.0. |
An alternative interface; its site lists RStan under “Other Packages”. |
| brms | Listed among the packages that import rstan on its CRAN page. | Depends on rstan; models are fit through it. |
| rstanarm | Listed among the packages that import rstan on its CRAN page. | Depends on rstan; models are fit through it. |
Researchers working in Python often meet the same ideas in other probabilistic-programming libraries, such as the one described in NumPyro. For a wider view of free software in this category, see free statistical software.
Frequently asked questions
What is rstan?
rstan is the R interface to the Stan probabilistic programming language. It compiles a Stan model and fits it from R, giving full Bayesian inference with MCMC, approximate inference by variational methods, or penalized maximum likelihood by optimization, according to its CRAN description.
How do I install rstan?
Install a C++ toolchain for your operating system, then run install.packages("rstan", repos = "https://cloud.r-project.org/", dependencies = TRUE) and verify with example(stan_model, package = "rstan", run.dontrun = TRUE), as the official Getting Started page describes.
Do I need to write Stan code to use rstan?
Not always. Packages such as brms and rstanarm import rstan and generate the Stan code for common models, while stan() accepts a Stan program you write yourself.
How many chains and iterations should I run?
The vignette’s example uses four chains of 2,000 iterations with 1,000 warmup. The Stan diagnostics guide asks for at least four chains and, for a final result, a bulk effective sample size above 400 with four chains and an R-hat below 1.01.
Can I ignore divergent transitions?
No. The Stan diagnostics guide says divergences after warmup cannot be safely ignored and recommends reparametrizing or using stronger priors before adjusting adapt_delta.
Sources
- CRAN: rstan package page, https://cran.r-project.org/web/packages/rstan/index.html (checked 2026-11-14)
- RStan Getting Started, https://github.com/stan-dev/rstan/wiki/RStan-Getting-Started (checked 2026-11-14)
- RStan vignette (About RStan), https://mc-stan.org/rstan/articles/rstan.html (checked 2026-11-14)
- Stan: Runtime warnings and convergence problems, https://mc-stan.org/learn-stan/diagnostics-warnings.html (checked 2026-11-14)
- CmdStanR, https://mc-stan.org/cmdstanr/ (checked 2026-11-14)
Data: Stan diagnostic thresholds mapped to rstan output
Thresholds from the Stan team's convergence and runtime-warning guidance, paired with the rstan output column or sampler parameter where each quantity appears. Compiled from the Stan diagnostics guide and the RStan vignette; each row states the threshold as the guide gives it.
| Diagnostic | Where it appears in rstan | Threshold or rule in the Stan guide | How the guide treats it |
|---|---|---|---|
| R-hat | Rhat column of print(fit) | Below 1.01 for a final result; below 1.1 often enough early | Run at least 4 chains |
| Effective sample size | n_eff column of print(fit) | Bulk-ESS above 100 times the number of chains (400 for 4 chains) for a final result; above 20 early | The RStan vignette calls n_eff a crude measure of effective sample size |
| Divergent transitions | divergent__ in get_sampler_params; red points in pairs() | Divergences after warmup cannot be safely ignored | Reparametrize or use stronger priors; adapt_delta is a last resort and above 0.99 seldom useful |
| Maximum treedepth | treedepth__ in get_sampler_params | Default limit 10; values of max_treedepth above 12 seldom useful | An efficiency issue, not a validity issue; likely safe to ignore if ESS and R-hat are good |
| E-BFMI | energy__ in get_sampler_params | Nominal threshold 0.3 | Listed in the guide among the sampler diagnostics |
Sources
- Stan: Runtime warnings and convergence problems (accessed 2026-11-14)
- RStan vignette (accessed 2026-11-14)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







