# NOT RUN {
#### example 1
library(rstan)
scode <- "
parameters {
real y[2];
}
model {
y[1] ~ normal(0, 1);
y[2] ~ double_exponential(0, 2);
}
"
fit1 <- stan(model_code = scode, iter = 10, verbose = FALSE)
print(fit1)
fit2 <- stan(fit = fit1, iter = 10000, verbose = FALSE)
## extract samples as a list of arrays
e2 <- extract(fit2, permuted = TRUE)
## using as.array on the stanfit object to get samples
a2 <- as.array(fit2)
#### example 2
#### the result of this package is included in the package
excode <- '
transformed data {
real y[20];
y[1] = 0.5796; y[2] = 0.2276; y[3] = -0.2959;
y[4] = -0.3742; y[5] = 0.3885; y[6] = -2.1585;
y[7] = 0.7111; y[8] = 1.4424; y[9] = 2.5430;
y[10] = 0.3746; y[11] = 0.4773; y[12] = 0.1803;
y[13] = 0.5215; y[14] = -1.6044; y[15] = -0.6703;
y[16] = 0.9459; y[17] = -0.382; y[18] = 0.7619;
y[19] = 0.1006; y[20] = -1.7461;
}
parameters {
real mu;
real<lower=0, upper=10> sigma;
vector[2] z[3];
real<lower=0> alpha;
}
model {
y ~ normal(mu, sigma);
for (i in 1:3)
z[i] ~ normal(0, 1);
alpha ~ exponential(2);
}
'
exfit <- stan(model_code = excode, save_dso = FALSE, iter = 500)
print(exfit)
plot(exfit)
# }
# NOT RUN {
## examples of specify argument `init` for function stan
## define a function to generate initial values that can
## be fed to function stan's argument `init`
# function form 1 without arguments
initf1 <- function() {
list(mu = 1, sigma = 4, z = array(rnorm(6), dim = c(3,2)), alpha = 1)
}
# function form 2 with an argument named `chain_id`
initf2 <- function(chain_id = 1) {
# cat("chain_id =", chain_id, "\n")
list(mu = 1, sigma = 4, z = array(rnorm(6), dim = c(3,2)), alpha = chain_id)
}
# generate a list of lists to specify initial values
n_chains <- 4
init_ll <- lapply(1:n_chains, function(id) initf2(chain_id = id))
exfit0 <- stan(model_code = excode, init = initf1)
stan(fit = exfit0, init = initf2)
stan(fit = exfit0, init = init_ll, chains = n_chains)
# }
Run the code above in your browser using DataLab