libary(rstan)
stan_demo <-
function(model = NULL, ...) {
MODELS_HOME <- file.path(system.file('include', package = 'rstan'),
"stansrc", "models")
MODELS <- dir(MODELS_HOME, pattern = paste0(model, ".stan", "$"),
recursive = TRUE, full.names = TRUE)
if(length(MODELS) == 0) {
stop("'model' not found; leave 'model' unspecified to see all choices")
}
else if(length(MODELS) > 1) {
MODELS <- select.list(MODELS)
model <- sub(".stan$", "", basename(MODELS))
}
MODEL_HOME <- dirname(MODELS)
STAN_ENV <- new.env()
if(file.exists(file.path(MODEL_HOME, paste0(model, "_generate_data.R")))) {
current_wd <- getwd()
on.exit(setwd(current_wd))
setwd(MODEL_HOME) # this might not work if MODEL_HOME is not writable
source(file.path(MODEL_HOME, paste0(model, "_generate_data.R")),
local = STAN_ENV, verbose = FALSE)
}
if(file.exists(file.path(MODEL_HOME, paste0(model, ".Rdata")))) {
source(file.path(MODEL_HOME, paste0(model, ".Rdata")),
local = STAN_ENV, verbose = FALSE)
}
return(stan(MODELS, model_name = model, data = STAN_ENV, ...))
}
check <- stan_demo("rats")