if (FALSE) {
# Load misty, lme4, nlme, and ggplot2 package
library(misty)
library(lme4)
# Load data set "Demo.twolevel" in the lavaan package
data("Demo.twolevel", package = "lavaan")
#-------------------------------------------------------------------------------
# Cluster mean centering, center() from the misty package
Demo.twolevel$x2.c <- center(Demo.twolevel$x2, type = "CWC",
cluster = Demo.twolevel$cluster)
# Compute group means, cluster.scores() from the misty package
Demo.twolevel$x2.b <- cluster.scores(Demo.twolevel$x2,
cluster = Demo.twolevel$cluster)
# Estimate random intercept model using the lme4 package
mod1 <- lmer(y1 ~ x2.c + x2.b + w1 + (1| cluster), data = Demo.twolevel,
REML = FALSE, control = lmerControl(optimizer = "bobyqa"))
# Estimate random intercept and slope model using the lme4 package
mod2 <- lmer(y1 ~ x2.c + x2.b + w1 + (1 + x2.c | cluster), data = Demo.twolevel,
REML = FALSE, control = lmerControl(optimizer = "bobyqa"))
#-------------------------------------------------------------------------------
# Example 1: Random intercept model
# Fixed slope estimates
fixef(mod1)
# Random effects variance-covariance matrix
as.data.frame(VarCorr(mod1))
# R-squared measures according to Rights and Sterba (2019)
multilevel.r2.manual(data = Demo.twolevel,
within = "x2.c", between = c("x2.b", "w1"),
gamma.w = 0.41127956,
gamma.b = c(0.01123245, -0.08269374, 0.17688507),
tau = 0.9297401,
sigma2 = 1.813245794)
#-------------------------------------------------------------------------------
# Example 2: Random intercept and slope model
# Fixed slope estimates
fixef(mod2)
# Random effects variance-covariance matrix
as.data.frame(VarCorr(mod2))
# R-squared measures according to Rights and Sterba (2019)
multilevel.r2.manual(data = Demo.twolevel,
within = "x2.c", between = c("x2.b", "w1"), random = "x2.c",
gamma.w = 0.41127956,
gamma.b = c(0.01123245, -0.08269374, 0.17688507),
tau = matrix(c(0.931008649, 0.004110479, 0.004110479, 0.017068857), ncol = 2),
sigma2 = 1.813245794)
}
Run the code above in your browser using DataLab