The “sampling” Function in R
Package: rstan
Purpose: Draws samples from a Stan model
General class: Bayesian inference
Required argument(s):
object: A stan model compiled with a function like “stan_model”.
data: List or environment containing data for the Stan model.
Notable optional arguments:
pars: Names of parameters to monitor and return samples for.
chains: Number of Markov chains to run.
cores: Number of CPU cores to use for parallelization.
iter: Number of iterations per chain.
warmup: Number of warmup iterations per chain.
thin: Thinning rate for the returned samples.
seed: Random seed for reproducibility.
Example:
# Load the rstan library
library(rstan)
# Define the Stan model code
model_code <- '
data {
int<lower=0> N;
real y[N];
}
parameters {
real mu;
real<lower=0> sigma;
}
model {
y ~ normal(mu, sigma);
}
'
# Compile the Stan model
model <- stan_model(model_code = model_code)
# Fit the model using MCMC sampling
N = 100
fit <- sampling(model, data = list(N = N, y = rnorm(N)))
# View summary of posterior samples
summary(fit)This example demonstrates how to use the “sampling” function from the rstan package to draw samples from a compiled Stan model. The function requires the result of fitting a Stan model (stanfit object) as input and allows specifying various optional arguments like parameters to monitor, number of chains, iterations, warmup, and more for controlling the sampling process.