The “stan” Function in R

  • Package: rstan

  • Purpose: Interface to Stan for Bayesian inference

  • General class: Statistical modeling

  • Required argument(s):

    • model_code or file: Stan model code or file containing the Stan model.

    • data: List or environment containing data for the Stan model.

  • Notable optional arguments:

    • pars: Parameters to monitor.

    • chains: Number of Markov chains.

    • cores: Number of cores to use for parallel computation.

    • iter: Number of iterations.

    • warmup: Number of warmup iterations.

    • thin: Thinning parameter.

    • seed: Random seed for reproducibility.

    • algorithm: Sampling algorithm (e.g., “NUTS”).

    • control: Control parameters for the sampling algorithm.

  • Example:

  • # Load the rstan library
    library(rstan)

    # Define the Stan model
    model_code <- '
    data {
    int<lower=0> N;
    real y[N];
    }
    parameters {
    real mu;
    real<lower=0> sigma;
    }
    model {
    y ~ normal(mu, sigma);
    }
    '

    # Generate synthetic data
    N <- 100
    data <- list(N = N, y = rnorm(N, 0, 1))

    # Run the Stan model
    fit <- stan(model_code = model_code, data = data, chains = 4, iter = 1000)
    summary(fit)

  • This example demonstrates how to use the “stan” function from the rstan package to perform Bayesian inference using a simple normal distribution model. It involves defining the Stan model, preparing data, running the model with optional arguments like chains and iterations, and then summarizing the results.

Previous
Previous

The “stan_model” Function in R

Next
Next

The “plan” Function in R