Learn R Programming

rstan (version 2.8.2)

expose_stan_functions: Expose user-defined Stan functions to Rfor testing and simulation

Description

Stan's language allows users to define their own functions in a functions block at the top of a Stan program. This utility uses sourceCpp to export those user-defined functions to the .GlobalEnv for testing inside Ror for doing posterior predictive simulations outside of the generated quantities block of a .stan program

Usage

expose_stan_functions(stanmodel)

Arguments

stanmodel
An object of stanmodel-class, stanfit-class, a list produced by stanc or a path to a .s

Value

  • The names of the new functions in .GlobalEnv are returned invisibly

Details

If a user-defined Stan function ends in _rng, then it can use the Boost pseudo-random number generator used by Stan. Note that a seed argument will be added to the formals on the R side that defaults to 0L but any non-negative integer can be passed as the seed the first time any user-defined function ending in _rng is called. In other words, the Boost pseudo-random number generator is initialized with the given seed but is declared with the static C++ keyword, meaning that it will not be reinitialized by subsequent calls to user-defined functions ending in _rng. If a user-defined Stan function ends in _lp, then it can modify the log-probability used by Stan to evaluate Metropolis proposals or as an objective function for optimization. Note that a lp__ argument will be added to the formals on the R side that defaults to zero. A double precision scalar may be passed to this argument when the function is called from R. Such a user-defined Stan function can terminate with return get_lp(); or can execute print(lp__); to verify that the calculation is correct.

See Also

sourceCpp

Examples

Run this code
# You could use a function like this to calculate the log-likelihood
  # for an observation over the posterior distribution to then use as
  # an ingredient to the calculation of the WAIC
  mc <- 
  '
  functions {
    vector logLik(int y, real x, vector beta) {
      vector[rows(beta)] logLik;
      for (i in 1:rows(beta)) {
        logLik[i] <- poisson_log_log(y, x * beta[i]);
      }
      return logLik;
    }
  }
  model {}
  '
  cppcode <- stanc(model_code = mc, model_name = "Demonstration")
  expose_stan_functions(cppcode)

Run the code above in your browser using DataLab