result <- BayesFactor::correlationBF(mtcars$mpg, mtcars$qsec)
resultBayes factor analysis
--------------
[1] Alt., r=0.333 : 4.416463 ±0%
Against denominator:
Null, rho = 0
---
Bayes factor type: BFcorrelation, Jeffreys-beta*
7. Posteriors
brmsbrms work (see last week’s instructions). If not, get in touch!
BayesFactor package allows us to compute Bayes factors using a mathematical trick without performing “full” Bayesian inferenceBayesFactor don’t contain the posterior, because it is not computed by default (the package focuses on estimating Bayes Factors in the most efficient way possible)posterior() function and specifying the number of iterations (i.e., the number of “draws”)Markov Chain Monte Carlo (MCMC) output:
Start = 1
End = 7
Thinning interval = 1
rho zeta
[1,] 0.4061366 0.4309760
[2,] 0.4595994 0.4968032
[3,] 0.3391690 0.3531532
[4,] 0.3391690 0.3531532
[5,] 0.5697774 0.6471931
[6,] 0.2361734 0.2407175
[7,] 0.3211367 0.3329140
Markov Chain Monte Carlo (MCMC) output:
Start = 1
End = 7
Thinning interval = 1
rho zeta
[1,] 0.4061366 0.4309760
[2,] 0.4595994 0.4968032
[3,] 0.3391690 0.3531532
[4,] 0.3391690 0.3531532
[5,] 0.5697774 0.6471931
[6,] 0.2361734 0.2407175
[7,] 0.3211367 0.3329140
rho and zeta (a transformed version of the correlation coefficient that is not important)simulate_results <- function(V1, V2) {
# Initialize dataframes
data_priors <- data.frame()
data_posteriors <- data.frame()
for(rscale in c(0.05, 0.1, 1/sqrt(27), 1/3, 1/sqrt(3), 1)) {
# Prior
prior <- data.frame(
y = dbeta(seq(0, 1, length.out=100), 1/rscale, 1/rscale),
x = seq(-1, 1, length.out=100),
rscale = insight::format_value(rscale)
)
# prior$y <- prior$y / max(prior$y) # Normalize y (for visualization)
data_priors <- rbind(data_priors, prior)
# Compute results
result <- BayesFactor::correlationBF(V1, V2, rscale=rscale)
# Sample posterior
posterior <- as.data.frame(BayesFactor::posterior(result, iterations=2000))
posterior$rscale <- insight::format_value(rscale)
data_posteriors <- rbind(data_posteriors, posterior)
}
# Make plot
ggplot(data_priors, aes(color=rscale)) +
geom_line(aes(x=x, y=y), linewidth=1, linetype="dashed") +
geom_density(data=data_posteriors, aes(x=rho), alpha=.2, linewidth=2) +
theme_bw() +
labs(x="Correlation Coefficient", y="Probability") +
coord_cartesian(xlim=c(-1, 1))
}









Thank you!
![]()