A Supplementary Code
One model, Three Implementations. There are a few ways to specify a hierarchical model in R. Below I describe three common frameworks that require varying levels of mathematical and programmatic competence. Frameworks with lower barriers for entry are great for researchers in many fields, but they lack fine control over the parameters in a model. As the framework complexity increases, so too does the ability to generate complex models that are typically not possible.
Novice
library(rstanarm)
stan_glmer(cbind(k, n-k) ~ 1 + x + (1 + x | G1) + (1 + x | G2),
family = binomial(link = "logit"),
data = dat)
Intermediate
library(rethinking)
ulam(alist(
k ~ binomial(n, pi)
logit(pi) <- (a + aG1[G1] + aG2[G2]) + (b + bG1[G1] + bG2[G2]) * x,
a ~ normal(0, 10),
aG1[G1] ~ normal(0, sd_aG1),
aG2[G2] ~ normal(0, sd_aG2),
c(sd_aG1, sd_aG2) ~ half_cauchy(0, 10),
b ~ normal(0, 10),
bG1[G1] ~ normal(0, sd_bG1),
bG2[G2] ~ normal(0, sd_bG2),
c(sd_bG1, sd_bG2) ~ half_cauchy(0, 10)
), data = dat, log_lik = TRUE)