if (requireNamespace("rstanarm", quietly = TRUE)) {
# Data:
dat_gauss <- data.frame(y = df_gaussian$y, df_gaussian$x)
# The "stanreg" fit which will be used as the reference model (with small
# values for `chains` and `iter`, but only for technical reasons in this
# example; this is not recommended in general):
fit <- rstanarm::stan_glm(
y ~ X1 + X2 + X3 + X4 + X5, family = gaussian(), data = dat_gauss,
QR = TRUE, chains = 2, iter = 500, refresh = 0, seed = 9876
)
# Projection onto an arbitrary combination of predictor terms (with a small
# value for `nclusters`, but only for the sake of speed in this example;
# this is not recommended in general):
prj <- project(fit, solution_terms = c("X1", "X3", "X5"), nclusters = 10,
seed = 9182)
prjmat <- as.matrix(prj)
### For further post-processing (e.g., via packages `bayesplot` and
### `posterior`), we will here ignore the fact that clustering was used
### (due to argument `nclusters` above). CAUTION: Ignoring the clustering
### is not recommended and only shown here for demonstrative purposes. A
### better solution for the clustering case is explained below.
# If the `bayesplot` package is installed, the output from
# as.matrix.projection() can be used there. For example:
if (requireNamespace("bayesplot", quietly = TRUE)) {
print(bayesplot::mcmc_intervals(prjmat))
}
# If the `posterior` package is installed, the output from
# as.matrix.projection() can be used there. For example:
if (requireNamespace("posterior", quietly = TRUE)) {
prjdrws <- posterior::as_draws_matrix(prjmat)
print(posterior::summarize_draws(
prjdrws,
"median", "mad", function(x) quantile(x, probs = c(0.025, 0.975))
))
}
### Better solution for post-processing clustered draws (e.g., via
### `bayesplot` or `posterior`): Don't ignore the fact that clustering was
### used. Instead, resample the clusters according to their weights (e.g.,
### via posterior::resample_draws()). However, this requires access to the
### cluster weights which is not implemented in `projpred` yet. This
### example will be extended as soon as those weights are accessible.
}
Run the code above in your browser using DataLab