set.seed(444)
library(bayestestR)
prior <- data.frame(
A = rnorm(1000),
B = rnorm(1000),
C = rnorm(1000)
)
posterior <- data.frame(
A = rnorm(1000, .4, 0.7),
B = rnorm(1000, -.2, 0.4),
C = rnorm(1000, 0, 0.5)
)
hyps <- c(
"A > B & B > C",
"A > B & A > C",
"C > A"
)
if (getRversion() > "3.5.0") {
(b <- bayesfactor_restricted(posterior, hypothesis = hyps, prior = prior))
as.numeric(b)
if (require("see") && require("patchwork")) {
i <- attr(b, "bool_results")[["posterior"]]
see::plots(
plot(estimate_density(posterior)),
# distribution **conditional** on the restrictions
plot(estimate_density(posterior[i[[hyps[1]]], ])) + ggplot2::ggtitle(hyps[1]),
plot(estimate_density(posterior[i[[hyps[2]]], ])) + ggplot2::ggtitle(hyps[2]),
plot(estimate_density(posterior[i[[hyps[3]]], ])) + ggplot2::ggtitle(hyps[3]),
guides = "collect"
)
}
}
if (FALSE) {
# rstanarm models
# ---------------
if (require("rstanarm") && require("emmeans")) {
fit_stan <- stan_glm(mpg ~ wt + cyl + am,
data = mtcars, refresh = 0
)
hyps <- c(
"am > 0 & cyl < 0",
"cyl < 0",
"wt - cyl > 0"
)
bayesfactor_restricted(fit_stan, hypothesis = hyps)
# emmGrid objects
# ---------------
# replicating http://bayesfactor.blogspot.com/2015/01/multiple-comparisons-with-bayesfactor-2.html
disgust_data <- read.table(url("http://www.learnbayes.org/disgust_example.txt"), header = TRUE)
contrasts(disgust_data$condition) <- contr.equalprior_pairs # see vignette
fit_model <- stan_glm(score ~ condition, data = disgust_data, family = gaussian())
em_condition <- emmeans(fit_model, ~condition)
hyps <- c("lemon < control & control < sulfur")
bayesfactor_restricted(em_condition, prior = fit_model, hypothesis = hyps)
# > # Bayes Factor (Order-Restriction)
# >
# > Hypothesis P(Prior) P(Posterior) BF
# > lemon < control & control < sulfur 0.17 0.75 4.49
# > ---
# > Bayes factors for the restricted model vs. the un-restricted model.
}
}
Run the code above in your browser using DataLab