Say I have 2 factor variables foo and bar which both contain the same levels "a", "b", and "c". Is there any way to specify in lme4 (or any other package) a model with random intercepts for foo and bar with correlation between intercepts with the same level? In other words, I think the effect of "a" in foo should be correlated with "a" in bar (similar for "b" and "c"). Formally, this might look something like:
for each level k in ["a", "b", "c"].
Here is some code which estimates sigma^2_foo and sigma^2_bar:
library(lme4)
levs <- c("a", "b", "c")
n <- 1000
df <- data.frame(y = rpois(n, 3.14),
foo = sample(levs, n, TRUE),
bar = sample(levs, n, TRUE))
mod <- glmer(y ~ (1 | foo) + (1 | bar), df, poisson)
> mod
Formula: y ~ (1 | foo) + (1 | bar)
Random effects:
Groups Name Std.Dev.
foo (Intercept) 0.009668
bar (Intercept) 0.006739
but of course misses the correlation term rho. Is it possible to add this correlation structure to this model?
UPDATE
In hope that it is helpful to people who are familiar with Stan, in Stan a basic implementation of this random effects model would look like this:
data {
int<lower = 1> num_data;
int<lower = 1> num_levels;
int<lower = 0> y[num_data];
int<lower = 1, upper = num_levels> foo_ix[num_data];
int<lower = 1, upper = num_levels> bar_ix[num_data];
}
parameters {
real alpha;
vector[num_levels] alpha_foo;
vector[num_levels] alpha_bar;
real<lower = 0.0> sigma_foo;
real<lower = 0.0> sigma_bar;
real<lower = -1.0, upper = 1.0> rho;
}
transformed parameters {
matrix[2, 2] Sigma;
Sigma[1, 1] = square(sigma_foo);
Sigma[2, 1] = rho * sigma_foo * sigma_bar;
Sigma[1, 2] = rho * sigma_foo * sigma_bar;
Sigma[2, 2] = square(sigma_bar);
}
model {
for (i in 1:num_levels) {
[alpha_foo[i], alpha_bar[i]] ~ multi_normal([0.0, 0.0], Sigma);
}
y ~ poisson_log(alpha + alpha_foo[foo_ix] + alpha_bar[bar_ix]);
}
