##
## Linear regression model
##
N = 100
x <- rnorm(N)
y <- .5 * x + rnorm(N)
dat <- cbind(y, x)
# no. of MCMC samples
iter = 600
# fit model
fit <- stan_glm(y ~ x, data = dat, iter = iter, quiet = TRUE)
# see results with MCMC diagnostics
print(fit)
##
## Custom prior distributions
##
PL <- list(
intercept = normal(0, 1),
beta = normal(0, 1),
sigma = student_t(10, 0, 2)
)
fit2 <- stan_glm(y ~ x, data = dat, prior = PL, iter = iter,
quiet = TRUE)
print(fit2)
# example prior for two covariates
pl <- list(beta = normal(c(0, 0),
c(1, 1))
)
##
## Poisson model for count data
## with county 'random effects'
##
data(sentencing)
# note: 'name' is county identifier
head(sentencing)
# denominator in standardized rate Y/E
# (observed count Y over expected count E)
# (use the log-denominator as the offest term)
sentencing$log_e <- log(sentencing$expected_sents)
# fit model
fit.pois <- stan_glm(sents ~ offset(log_e),
re = ~ name,
family = poisson(),
data = sentencing,
iter = iter, quiet = TRUE)
# Spatial autocorrelation/residual diagnostics
sp_diag(fit.pois, sentencing)
# summary of results with MCMC diagnostics
print(fit.pois)
# \donttest{
# MCMC diagnostics plot: Rhat values should all by very near 1
rstan::stan_rhat(fit.pois$stanfit)
# effective sample size for all parameters and generated quantities
# (including residuals, predicted values, etc.)
rstan::stan_ess(fit.pois$stanfit)
# or for a particular parameter
rstan::stan_ess(fit.pois$stanfit, "alpha_re")
# }
##
## Visualize the posterior predictive distribution
##
# plot observed values and model replicate values
yrep <- posterior_predict(fit.pois, S = 65)
y <- sentencing$sents
ltgray <- rgb(0.3, 0.3, 0.3, 0.5)
plot(density(yrep[1,]), col = ltgray,
ylim = c(0, 0.014), xlim = c(0, 700),
bty = 'L', xlab = NA, main = NA)
for (i in 2:nrow(yrep)) lines(density(yrep[i,]), col = ltgray)
lines(density(sentencing$sents), col = "darkred", lwd = 2)
legend("topright", legend = c('Y-observed', 'Y-replicate'),
col = c('darkred', ltgray), lwd = c(1.5, 1.5))
# plot replicates of Y/E
E <- sentencing$expected_sents
# set plot margins
old_pars <- par(mar=c(2.5, 3.5, 1, 1))
# plot yrep
plot(density(yrep[1,] / E), col = ltgray,
ylim = c(0, 0.9), xlim = c(0, 7),
bty = 'L', xlab = NA, ylab = NA, main = NA)
for (i in 2:nrow(yrep)) lines(density(yrep[i,] / E), col = ltgray)
# overlay y
lines(density(sentencing$sents / E), col = "darkred", lwd = 2)
# legend, y-axis label
legend("topright", legend = c('Y-observed', 'Y-replicate'),
col = c('darkred', ltgray), lwd = c(1.5, 1.5))
mtext(side = 2, text = "Density", line = 2.5)
# return margins to previous settings
par(old_pars)
Run the code above in your browser using DataLab