Random Intercept & Slope Models in R
Random Intercept & Slope Models in R
1/19/2023
Set up
Libraries
Read in Data
hsb1
hsb2
Merging hsb1 and hsb2
Some exploratory looks at the data
Graphs of the data
Create More Variables
Model Fitting
Null HLM
Computing ICC (and function)
Random intercept and slope for centered ses
Random intercept and slope & meanses for ses
Graphs around page 20 of Lecture Notes
Discrete Level 1 predictors (fixed effects)
Plot of population average model
Plot of variance function
Alternative Treatment of categorical predictors
Random Descrete Predictors
Alternative Model b1
Another parameterization
Bad Parameteriation
This Works.
And this works.
Cross-level interactions
Models Refinements
Drop non-signicant Interaction
p127 Big model
Other tricks to get models to converge
The document contains R script used for the high school and beyond analyses given in the lecture notes.
Set up
Libraries
I am adding one package that we haven't used before, "optimx". This allows us to change the algorithm and solves as least one estimation problem
that we run into with these models and data.
library(lme4)
library(lmerTest)
library(lattice)
library(texreg)
library(optimx)
library(stargazer)
Read in Data
This is where the data live on my computer:
setwd('D:/Dropbox/edps587/lectures/4 randomslope')
The reading in of data and merging files is the same as in the "Random Intercepts Models in R" Rmarkdown file.
hsb1
hsb1 <- [Link](file="[Link]", header=TRUE)
# variable names
names(hsb1)
[Link] 1/22
2/1/23, 10:10 AM Edpsy 587: Random Intercept and Slope Models using R
## [1] "id" "minority" "female" "ses" "mathach"
## [1] 7185 5
tail(hsb1)
hsb2
hsb2 <- [Link](file="[Link]", header=TRUE)
names(hsb2)
dim(hsb2)
## [1] 160 7
tail(hsb2)
I know that the data sets are already sorted by the school id, which will be the matching variable.
## [1] 7185 11
names(hsb)
## [1] 160
[Link] 2/22
2/1/23, 10:10 AM Edpsy 587: Random Intercept and Slope Models using R
## [1] "id" "minority" "female" "ses" "mathach" "size"
## [7] "sector" "pracad" "disclim" "himinty" "meanses" "cses"
##
## ==================================================================
## Statistic N Mean St. Dev. Min Pctl(25) Pctl(75) Max
## ------------------------------------------------------------------
## ses 7,185 0.0001 0.779 -3.758 -0.538 0.602 2.692
## mathach 7,185 12.748 6.878 -2.832 7.275 18.317 24.993
## size 7,185 1,056.862 604.172 100 565 1,436 2,713
## pracad 7,185 0.534 0.251 0.000 0.320 0.700 1.000
## disclim 7,185 -0.132 0.944 -2.416 -0.817 0.460 2.756
## himinty 7,185 0.280 0.449 0 0 1 1
## meanses 7,185 0.006 0.414 -1.188 -0.317 0.333 0.831
## ------------------------------------------------------------------
##
## 0 1
## 5211 1974
table(hsb$female)
##
## 0 1
## 3390 3795
table(hsb$sector)
##
## 0 1
## 3642 3543
[Link] 3/22
2/1/23, 10:10 AM Edpsy 587: Random Intercept and Slope Models using R
What does data look like for just one school and include linear regression line?
We might want to look at a bunch of schools but 160 graphs is a lot, so we'll take a random sample of 20 and just look at these.
[Link] 4/22
2/1/23, 10:10 AM Edpsy 587: Random Intercept and Slope Models using R
However, we would like to also put in regression lines for each of these schools, which mean that we have to change what is in type,
What to graphs look like when we used school mean centered SES?
r xyplot(mathach ~ cses | id, data=subset, [Link]='black', type=c('p','r'), main='Math Achievement by School Centered SES',
[Link] 5/22
2/1/23, 10:10 AM Edpsy 587: Random Intercept and Slope Models using R
It is also useful to look at all the regressions in a single plot; however, I need consequtive integers to index the school (i.e., index that goes from 1
- 160)
To make the graph, we first set up a data frame that has the specifies the title, axis labels, etc. Note that type='n' doesn't plot any data
To make the graph, we first set up a data frame that has the specifies the title, axis labels, etc. ane then add in the regression lines Note that
type='n' doesn't plot any data
plot(hsb$ses,hsb$mathach,type = 'n',
ylim = c(-10, 30),
xlim = c(-3, 3),
[Link] = 1.5,
xlab = 'SES',
ylab = "Math Scores",
main = "Separate Regression for Each School "
)
for(i in 1:nschools){
sub <- hsb[which(hsb$sch_id==i),]
fitted <- fitted(lm(mathach~ses,data=sub))
lines(sub$ses,fitted,col=i)
}
The following code prodcues the graph on page 45 of the lecture note on random intercept and slope models. This is the variance function
[Link] 6/22
2/1/23, 10:10 AM Edpsy 587: Random Intercept and Slope Models using R
x <- seq(from=-2, to=2, by=.1)
plot(x,total,type = 'l',
[Link] = 1.5,
col='blue',
xlim=c(-2,2),
xlab = 'Value of x',
ylab = "Estimated Variance of x",
main = "Variance Function: Illustration of Heteroscedasticity"
)
At this point you might want to consider saving teh data to a file, especially if you plan to use it again,
Model Fitting
Null HLM
#
# Random inercept / empty HLM / Null model / RANDOM effects ANOVA
#
[Link] 7/22
2/1/23, 10:10 AM Edpsy 587: Random Intercept and Slope Models using R
## Random effects:
## Groups Name Variance [Link].
## id (Intercept) 8.553 2.925
## Residual 39.148 6.257
## Number of obs: 7185, groups: id, 160
##
## Fixed effects:
## Estimate Std. Error df t value Pr(>|t|)
## (Intercept) 12.6371 0.2436 157.6209 51.87 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## [1] 0.1793044
## [1] 0.1793109
Best yet, function since we do this over and over, use the following function that I wrote:
icc <- function(modl){
vars <- [Link](VarCorr(modl))[4]
total <- sum(vars)
tau00 <- vars[1,1]
icc <- tau00/total
return(icc)
}
## [1] 0.1793109
icc(model1)
## [1] 0.1887876
[Link] 8/22
2/1/23, 10:10 AM Edpsy 587: Random Intercept and Slope Models using R
##
## ===============================================================
## Random Intercept Models
## ------------------------------------------
## Null RI ses
## ---------------------------------------------------------------
## (Intercept) 12.64 (0.24) *** 12.65 (0.24) ***
## cses 2.19 (0.11) ***
## ---------------------------------------------------------------
## AIC 47121.81 46728.41
## BIC 47142.45 46755.93
## Log Likelihood -23557.91 -23360.21
## Num. obs. 7185 7185
## Num. groups: id 160 160
## Var: id (Intercept) 8.55 8.61
## Var: Residual 39.15 37.01
## ===============================================================
## *** p < 0.001; ** p < 0.01; * p < 0.05
Below we fit a model with both a random intercept and random slope for cses.
summary(model2 <- lmer(mathach ~ 1 + cses + (1 + cses| id), data=hsb, REML=FALSE))
[Link](VarCorr(model2))[4]
## vcov
## 1 8.62127569
## 2 0.67826037
## 3 0.05031215
## 4 36.70001845
deviance(model2)
## [1] 46710.98
##
## ==========================================================================================
## Random Intercept Random Slope
## ------------------------------------------ --------------------
## Null cses ces
## ------------------------------------------------------------------------------------------
## (Intercept) 12.64 (0.24) *** 12.65 (0.24) *** 12.65 (0.24) ***
## cses 2.19 (0.11) *** 2.19 (0.13) ***
## ------------------------------------------------------------------------------------------
## AIC 47121.81 46728.41 46722.98
## BIC 47142.45 46755.93 46764.26
## Log Likelihood -23557.91 -23360.21 -23355.49
## Num. obs. 7185 7185 7185
## Num. groups: id 160 160 160
## Var: id (Intercept) 8.55 8.61 8.62
## Var: Residual 39.15 37.01 36.70
## Var: id cses 0.68
## Cov: id (Intercept) cses 0.05
[Link] 9/22
2/1/23, 10:10 AM Edpsy 587: Random Intercept and Slope Models using R
## ==========================================================================================
## *** p < 0.001; ** p < 0.01; * p < 0.05
For the graph on or about page 21 of lecture notes, sample of fitted school specific regression lines
[Link] 10/22
2/1/23, 10:10 AM Edpsy 587: Random Intercept and Slope Models using R
[Link] 11/22
2/1/23, 10:10 AM Edpsy 587: Random Intercept and Slope Models using R
[Link] <- [Link](VarCorr(model2))[4]
[Link]<- [Link][1,] + 2*[Link][3,]*ses2 + [Link][2,]*(ses2**2) + [Link][4,]
plot(ses2,[Link],type = 'l',
[Link] = 1.5,
col='blue',
xlim=c(-2,3),
ylim=c(45,52),
xlab = 'School Mean Centered SES',
ylab = "Estimated Variance of Math Scores",
main = "HSB: Variance Function"
)
# random inercept
abline(a=sum([Link]), b=0, col='red')
legend(-2,52,
c('Random Intercept & Slope','Random Intercept'),
lty=c(1,1),
lwd=c(2.5,2.5),
col=c('blue','red'))
[Link] 12/22
2/1/23, 10:10 AM Edpsy 587: Random Intercept and Slope Models using R
[Link](VarCorr(model.d1))[4]
## vcov
## 1 6.2628806
## 2 0.4800510
## 3 -0.3001918
## 4 35.6631590
Since we have fit a number of models, let's see where we are at.
screenreg(list(model1,model2,model.d1),
[Link]=c("RI","RI and RS","Discrete fixed"))
##
## ======================================================================
## RI RI and RS Discrete fixed
## ----------------------------------------------------------------------
## (Intercept) 12.65 *** 12.65 *** 14.14 ***
## (0.24) (0.24) (0.24)
## cses 2.19 *** 2.19 *** 1.89 ***
## (0.11) (0.13) (0.12)
## female -1.22 ***
## (0.16)
## minority -3.12 ***
## (0.21)
## ----------------------------------------------------------------------
## AIC 46728.41 46722.98 46466.95
## BIC 46755.93 46764.26 46521.99
## Log Likelihood -23360.21 -23355.49 -23225.48
## Num. obs. 7185 7185 7185
## Num. groups: id 160 160 160
## Var: id (Intercept) 8.61 8.62 6.26
## Var: Residual 37.01 36.70 35.66
## Var: id cses 0.68 0.48
## Cov: id (Intercept) cses 0.05 -0.30
## ======================================================================
## *** p < 0.001; ** p < 0.01; * p < 0.05
[Link] 13/22
2/1/23, 10:10 AM Edpsy 587: Random Intercept and Slope Models using R
plot(ses2,total.d1,type = 'l',
[Link] = 1.5,
col='blue',
xlim=c(-2,3),
xlab = 'School Mean Centered SES',
ylab = "Estimated Variance of Math Scores",
main = "HSB: Variance Function (discrete fixed)"
)
summary(model.00 <- lmer(mathach ~ 1 + cses + gender + race + (1 + cses| id), data=hsb, REML=FALSE))
[Link] 14/22
2/1/23, 10:10 AM Edpsy 587: Random Intercept and Slope Models using R
## Linear mixed model fit by maximum likelihood . t-tests use Satterthwaite's
## method [lmerModLmerTest]
## Formula: mathach ~ 1 + cses + gender + race + (1 + cses | id)
## Data: hsb
##
## AIC BIC logLik deviance [Link]
## 46467.0 46522.0 -23225.5 46451.0 7177
##
## Scaled residuals:
## Min 1Q Median 3Q Max
## -3.1821 -0.7199 0.0323 0.7602 2.8373
##
## Random effects:
## Groups Name Variance [Link]. Corr
## id (Intercept) 6.2629 2.5026
## cses 0.4801 0.6929 -0.17
## Residual 35.6632 5.9719
## Number of obs: 7185, groups: id, 160
##
## Fixed effects:
## Estimate Std. Error df t value Pr(>|t|)
## (Intercept) 14.1422 0.2351 232.8885 60.163 < 2e-16 ***
## cses 1.8946 0.1224 157.1366 15.472 < 2e-16 ***
## gender1 -1.2199 0.1643 7057.9081 -7.424 1.27e-13 ***
## race1 -3.1188 0.2103 5764.5187 -14.834 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Correlation of Fixed Effects:
## (Intr) cses gendr1
## cses -0.114
## gender1 -0.367 0.045
## race1 -0.250 0.139 0.012
# To get variance
[Link](VarCorr(model.00))[4]
## vcov
## 1 6.2628806
## 2 0.4800510
## 3 -0.3001918
## 4 35.6631590
This should yield that same fit statistics, interpretation of effects, significance of effects, etc.
summary(model.b1 <- lmer(mathach ~ 1 + cses + female + race + (1 + cses + female| id), data=hsb, REML=FALSE))
[Link](VarCorr(model.b1))[4]
## vcov
## 1 6.9181349
## 2 0.4569283
## 3 0.7857687
## 4 -0.2066691
## 5 -0.9444765
[Link] 15/22
2/1/23, 10:10 AM Edpsy 587: Random Intercept and Slope Models using R
## 6 -0.1727498
## 7 35.5342275
Alternative Model b1
summary(model.ab1 <- lmer(mathach ~ 1 + cses + gender + race + (1 + cses + gender| id), data=hsb, REML=FALSE))
[Link](VarCorr(model.ab1))[4]
## vcov
## 1 6.9181349
## 2 0.4569283
## 3 0.7857687
## 4 -0.2066691
## 5 -0.9444765
## 6 -0.1727498
## 7 35.5342275
Another parameterization
summary(model.b2 <- lmer(mathach ~ 1 + cses + hsb$male + race + (1 + cses + hsb$male| id), data=hsb, REML=FALSE))
[Link](VarCorr(model.b2))[4]
[Link] 16/22
2/1/23, 10:10 AM Edpsy 587: Random Intercept and Slope Models using R
## vcov
## 1 5.8148277
## 2 0.4570253
## 3 0.7858424
## 4 -0.3792555
## 5 0.1588552
## 6 0.1727952
## 7 35.5341774
Bad Parameteriation
Note that this one does not work --- does not converge. Why?
# Model c.
summary(model.c <- lmer(mathach ~ 1 + cses + hsb$male + race + (0 + cses + male + female + minority| id), data=hsb, REML=FALSE))
[Link](VarCorr(model.b2))[4]
## vcov
## 1 5.8148277
## 2 0.4570253
## 3 0.7858424
## 4 -0.3792555
## 5 0.1588552
## 6 0.1727952
## 7 35.5341774
This Works.
Why?
summary([Link] <- lmer(mathach ~ 1 + cses + female + minority + (1 + cses + female + minority | id), data=hsb, REML=FALSE))
[Link] 17/22
2/1/23, 10:10 AM Edpsy 587: Random Intercept and Slope Models using R
## female 0.8501 0.922 -0.43 -0.23
## minority 1.9127 1.383 0.29 -0.66 0.12
## Residual 35.3086 5.942
## Number of obs: 7185, groups: id, 160
##
## Fixed effects:
## Estimate Std. Error df t value Pr(>|t|)
## (Intercept) 14.1501 0.2358 149.3294 60.016 < 2e-16 ***
## cses 1.8726 0.1198 151.3902 15.635 < 2e-16 ***
## female -1.2581 0.1832 118.4607 -6.868 3.21e-10 ***
## minority -3.2011 0.2503 116.9638 -12.790 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Correlation of Fixed Effects:
## (Intr) cses female
## cses -0.037
## female -0.492 0.002
## minority -0.104 -0.007 0.032
You're on your own for the figures --- cut, paste & edit code for similar figures
Cross-level interactions
When a level 2 variable, say \(z_{j}\) is a predictor of a random effect (or fixed level 1 variable), we add the variable to the fixed/structural part of
the formula. If \(z_{j}\) is a predictor of the slope for \(x_{ij}\), the formula would be \[y_{ij} \leftarrow 1 + x_{ij} + z_{j} + z_{j}*x_{ij} + (1 +
x_{ij} | \mbox{id}) \] In other words, we add an interaction between \(z_{j}\) and \(x_{ij}\).
summary(model.3 <- lmer(mathach ~ 1 + cses + meanses + cses*meanses + (1 + cses| id), data=hsb, REML=FALSE))
[Link] 18/22
2/1/23, 10:10 AM Edpsy 587: Random Intercept and Slope Models using R
##
## Fixed effects:
## Estimate Std. Error df t value Pr(>|t|)
## (Intercept) 12.6589 0.1482 155.6452 85.414 <2e-16 ***
## cses 2.1960 0.1272 156.2691 17.264 <2e-16 ***
## meanses 5.8700 0.3589 155.3156 16.357 <2e-16 ***
## cses:meanses 0.2863 0.3169 171.1168 0.903 0.368
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Correlation of Fixed Effects:
## (Intr) cses meanss
## cses -0.083
## meanses -0.004 0.000
## cses:meanss 0.000 0.042 -0.080
[Link](VarCorr(model.3))[4]
## vcov
## 1 2.6443444
## 2 0.6496455
## 3 -0.2574434
## 4 36.7155992
Models Refinements
Drop non-signicant Interaction
summary(model.4 <- lmer(mathach ~ 1 + cses + meanses + (1 + cses| id), data=hsb, REML=FALSE))
[Link] 19/22
2/1/23, 10:10 AM Edpsy 587: Random Intercept and Slope Models using R
##
## Random effects:
## Groups Name Variance [Link]. Corr
## id (Intercept) 1.9538 1.3978
## cses 0.4039 0.6355 0.39
## female 0.7469 0.8642 -0.74 -0.14
## minority 1.6017 1.2656 -0.18 -0.84 -0.03
## Residual 35.3375 5.9445
## Number of obs: 7185, groups: id, 160
##
## Fixed effects:
## Estimate Std. Error df t value Pr(>|t|)
## (Intercept) 1.148e+01 5.008e-01 1.743e+02 22.931 < 2e-16 ***
## cses 1.887e+00 1.203e-01 1.519e+02 15.688 < 2e-16 ***
## female -1.281e+00 1.737e-01 1.385e+02 -7.376 1.36e-11 ***
## minority -3.075e+00 2.429e-01 1.595e+02 -12.659 < 2e-16 ***
## meanses 3.168e+00 4.236e-01 1.428e+02 7.479 6.96e-12 ***
## size 6.937e-04 2.093e-04 1.511e+02 3.314 0.001150 **
## sector 8.130e-01 3.776e-01 1.410e+02 2.153 0.033003 *
## pracad 2.722e+00 7.952e-01 1.532e+02 3.423 0.000796 ***
## disclim -4.086e-01 1.753e-01 1.517e+02 -2.331 0.021073 *
## himinty 1.856e-01 3.142e-01 1.596e+02 0.591 0.555590
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Correlation of Fixed Effects:
## (Intr) cses female minrty meanss size sector pracad disclm
## cses 0.027
## female -0.287 0.018
## minority -0.020 -0.032 0.013
## meanses 0.490 0.005 0.002 0.089
## size -0.600 -0.005 0.025 -0.036 -0.181
## sector -0.147 -0.004 0.023 -0.044 0.025 0.251
## pracad -0.728 -0.001 0.060 -0.019 -0.609 0.112 -0.338
## disclim -0.306 0.000 0.093 -0.029 -0.022 -0.044 0.505 0.205
## himinty 0.157 -0.051 -0.027 -0.308 0.400 -0.178 -0.106 -0.198 -0.048
## fit warnings:
## Some predictor variables are on very different scales: consider rescaling
We can do a bit better by rescaling school size which has a very different scale
[Link](VarCorr(model.5))[4]
## vcov
## 1 1.95419176
[Link] 20/22
2/1/23, 10:10 AM Edpsy 587: Random Intercept and Slope Models using R
## 2 0.40392581
## 3 0.74693929
## 4 1.60152870
## 5 0.34521147
## 6 -0.88947968
## 7 -0.31798090
## 8 -0.07933781
## 9 -0.67179567
## 10 -0.02783238
## 11 35.33742752
In this model (see aroun) p127 of lecture notes), we do make some changes to the model by adding sector as cross-level (i.e. predictor at level 2)
and dropping random gender.
The thing that really help is changing the optimizer. This is done below using "control"
[Link](VarCorr(model.6))[4]
[Link] 21/22
2/1/23, 10:10 AM Edpsy 587: Random Intercept and Slope Models using R
## vcov
## 1 1.22579595
## 2 0.16458404
## 3 0.77736156
## 4 0.15183165
## 5 -0.06946504
## 6 -0.13709806
## 7 35.46009963
[Link](VarCorr(model.7))[4]
## vcov
## 1 1.300117
## 2 35.631569
[Link] 22/22