The “stan_model” Function in R

  • Package: rstan

  • Purpose: Compiles Stan model code

  • General class: Model compilation

  • Required argument(s):

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

  • Notable optional arguments:

    • model_name: Name for the compiled model.

    • verbose: Print compilation information.

    • allow_undefined: Allow undefined function calls in the Stan model.

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

    # Check model details
    print(model)

    # Demonstrate model fit
    N = 100
    sampling(model, data = list(N = N, y = rnorm(N, 0, 1)))

  • This example demonstrates how to use the “stan_model” function from the rstan package to compile Stan model code. You can provide the Stan model code directly or specify a file containing the code. The compiled model can then be used for Bayesian inference using functions like “sampling” from the same package.

Previous
Previous

The “sampling” Function in R

Next
Next

The “stan” Function in R