Writing Stan Models in R
Define data blocks, parameters, and the model block in Stan syntax.
What Is Stan?
Stan is a probabilistic programming language for Bayesian statistical modelling. RStan is the R interface to Stan. You write the model in Stan's language (C++-like), and Stan compiles it to efficient C++ code that runs Hamiltonian Monte Carlo (HMC) sampling to approximate the posterior.
# Stan installation check
library(rstan)
# Check version
cat('RStan version:', as.character(packageVersion('rstan')), '\n')
# Enable parallel chains
options(mc.cores = parallel::detectCores())
# Reuse compiled models across sessions
rstan_options(auto_write = TRUE)
cat('Stan ready. Cores:', parallel::detectCores(), '\n')Stan Model Structure
A Stan model has up to six named blocks: data, transformed data, parameters, transformed parameters, model, and generated quantities. The three essential blocks are data, parameters, and model.
library(rstan)
# Stan model as a character string in R
stan_code <- '
data {
int<lower=0> N; // number of observations
vector[N] x; // predictor
vector[N] y; // response
}
parameters {
real alpha; // intercept
real beta; // slope
real<lower=0> sigma; // noise (must be positive)
}
model {
// Priors
alpha ~ normal(0, 10);
beta ~ normal(0, 10);
sigma ~ exponential(1);
// Likelihood
y ~ normal(alpha + beta * x, sigma);
}
'
cat('Stan model defined as a string in R\n')
cat('Blocks: data, parameters, model\n')All lessons in this course
- Introduction to Bayesian Thinking
- Writing Stan Models in R
- MCMC Sampling and Diagnostics
- Posterior Predictive Checks