I am not sure how lme4
internally recognizes and deals with group predictor variables, but the logic of it is exactly what you pointed out. Individual variables vary within groups whereas group variables are constant within a group but differ between groups. The key to all this is telling lmer
what your grouping structure is. If you had indicated a different variable as your group, e.g., school district, then the school variables would vary within districts and would be considered "lower level" predictors.
You can also calculate the school means of individual variables and include those means as predictors in your lmer
model:
library(dplyr)
df <- df %>% group_by(school) %>% mutate(mn_sex = mean(sex), mn_age = mean(age)) %>% ungroup()
m <- lmer(y ~ age + mn_age + sex + mn_sex + (1|school), data=df)
This models the within-school (age
, sex
) and between-school (mn_age
, mn_sex
) associations explicitly so that you can see the relations between these predictors and the outcome at the different levels represented in your model. In this formulation, the mn_
variable coefficients represent a test of whether the within- and between-school associations with the outcome are equivalent (non-significant mn_
coefficient) or different (significant mn_
coefficient) and by how much (subtract mn_
coefficient from the uncentered coefficient of th same variable: mn_age - age
).
With regards to your question about rank, note that the way you represented your data in the first table rank varies within schools and thus is not a group level variable. Perhaps you made a typo? At any rate, lmer
will appropriately model any variable that does not vary within groups as explaining the group-level variation in the outcome. As a test, run two models and compare the school variance estimates. You will see that in m2, below, only the variance of the School term decreases:
m1 <- lmer(y ~ age + (1|school), data=df)
m2 <- lmer(y ~ age + rank + (1|school), data=df)