Skip to content

Instantly share code, notes, and snippets.

@JimGrange
Created June 1, 2023 06:41
Show Gist options
  • Save JimGrange/5346e74c2d4a5bb405735bca60920942 to your computer and use it in GitHub Desktop.
Save JimGrange/5346e74c2d4a5bb405735bca60920942 to your computer and use it in GitHub Desktop.
Bayes factor for contingency table
library(tidyverse)
library(BayesFactor)
# set seed for reproducibility
set.seed(234)
# define population-level parameters
p_text_yes <- 0.5
p_video_yes <- 0.5
# sample size
n <- 300
# simulate data using population-level parameters
data <- tibble(
medium = rep(c("text", "video"), each = n),
judgement = rbinom(2 * n,
size = 1,
prob = if_else(medium == "text", p_text_yes, p_video_yes))
) %>%
mutate(judgement = case_when(judgement == 1 ~ "yes",
judgement == 0 ~ "no"))
# collapse into a contingency table
contingency_table <- table(data$medium,
data$judgement)
# Calculate the Bayes factor for the contingency table
bf <- contingencyTableBF(contingency_table,
sampleType = "indepMulti",
fixedMargin = "rows")
# get bf for null vs alternative
1/bf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment