37  Doing the same multi-level model with R and Stata

Published

October 26, 2023

This post is a demo for doing the same multi-level models with R and stata. R’s multilevel models are mostly done with lme4 and nlme. Stata’s multilevel models are mostly done with mixed and menl. The two packages are not exactly the same. mixed does in fact support several residual covariance structures via its residuals() option (e.g. residuals(exponential, t(year)), as well as ar, ma, toeplitz, etc.) — so it’s not that mixed cannot handle a structured residual at all, but menl’s nonlinear-mixed-model framework gives more flexibility to combine that with custom nonlinear mean/random-effect specifications (like the CEM model below), which is why we reach for it here. Likewise, in R lme4’s “lmer” does not allow this specification. We have to use nlme. But it’s good to know how to do the same thing in both packages.

For example, we want to do a consensus emergence model (CEM) as described in Lang, Bliese, and Voogt (2018). The CEM model is basically a growth model with the residual being a exponential function of the time variable. We want to do the same thing in both R and stata.

We start with simpler models.

37.1 Stata and R syntax comparison for the same three level model

We run a three level model specified in stata with mixed and menl. In R with nlme and lme4. This is a random intercept model. Only intercept is varying for each unit at each level. In this data set supposedly state is nested within region. There are situations that levels are not nested, then we need to specify cross effect models. We do not discuss that here. One point to watch: nlme’s lme function expects the grouping factors in the random specification ordered from the highest level down. Here state is nested within region, so region must be listed before state; reversing the order leads lme to treat regions as nested within states, which is not the intended structure.

There are different ways to specify this model in nlme. I show two ways here (including lme2 which is commented out).

37.1.1 Stata

Code

* let's see how to use menl
webuse productivity
* to replicate mixed with menl
mixed gsp || region: || state:
menl gsp = {b1:},  define(b1: U1[region] UU1[region>state])
(Public capital productivity)


Performing EM optimization ...

Performing gradient-based optimization: 
Iteration 0:  Log likelihood =  200.86162  
Iteration 1:  Log likelihood =  200.86162  

Computing standard errors ...

Mixed-effects ML regression                                Number of obs = 816

        Grouping information
        -------------------------------------------------------------
                        |     No. of       Observations per group
         Group variable |     groups    Minimum    Average    Maximum
        ----------------+--------------------------------------------
                 region |          9         51       90.7        136
                  state |         48         17       17.0         17
        -------------------------------------------------------------

                                                           Wald chi2(0)  =   .
Log likelihood =  200.86162                                Prob > chi2   =   .

------------------------------------------------------------------------------
         gsp | Coefficient  Std. err.      z    P>|z|     [95% conf. interval]
-------------+----------------------------------------------------------------
       _cons |   10.65961   .2503806    42.57   0.000     10.16887    11.15035
------------------------------------------------------------------------------

------------------------------------------------------------------------------
  Random-effects parameters  |   Estimate   Std. err.     [95% conf. interval]
-----------------------------+------------------------------------------------
region: Identity             |
                  var(_cons) |   .4376123   .2697616        .13073    1.464887
-----------------------------+------------------------------------------------
state: Identity              |
                  var(_cons) |   .6080626   .1382733      .3893904    .9495357
-----------------------------+------------------------------------------------
               var(Residual) |   .0246633   .0012586      .0223159    .0272577
------------------------------------------------------------------------------
LR test vs. linear model: chi2(2) = 2750.56               Prob > chi2 = 0.0000

Note: LR test is conservative and provided only for reference.


Obtaining starting values by EM:

Alternating PNLS/LME algorithm:

Iteration 1:  Linearization log likelihood =  200.86162
Iteration 2:  Linearization log likelihood =  200.86162

Computing standard errors:

Mixed-effects ML nonlinear regression           Number of obs     =        816

      Grouping information
      ------------------------------------------------------------------
                           |     No. of        Observations per group
                      Path |     groups    Minimum    Average    Maximum
      ---------------------+--------------------------------------------
                    region |          9         51       90.7        136
              region>state |         48         17       17.0         17
      ------------------------------------------------------------------


Linearization log likelihood =  200.86162

          b1: U1[region] UU1[region>state]

------------------------------------------------------------------------------
         gsp | Coefficient  Std. err.      z    P>|z|     [95% conf. interval]
-------------+----------------------------------------------------------------
b1           |
       _cons |   10.65961   .2505341    42.55   0.000     10.16857    11.15065
------------------------------------------------------------------------------

------------------------------------------------------------------------------
  Random-effects parameters  |   Estimate   Std. err.     [95% conf. interval]
-----------------------------+------------------------------------------------
region: Identity             |
                     var(U1) |   .4376119   .2686479      .1313834    1.457598
-----------------------------+------------------------------------------------
region>state: Identity       |
                    var(UU1) |   .6080625   .1381527      .3895418    .9491666
-----------------------------+------------------------------------------------
               var(Residual) |   .0246633   .0012586      .0223159    .0272577
------------------------------------------------------------------------------

37.1.2 R

The data are productivity: 816 observations of gross state product, with 48 states nested in 9 regions, 17 years each. The model is intercept-only with random intercepts at both levels.

These two R packages return same results. Note that lmer reports variance, while lme reports standard deviation.

And they do: lmer reports variances of 0.60775 for state-within-region and 0.50977 for region, with a residual of 0.02466; lme reports the corresponding standard deviations 0.77958, 0.71398 and 0.15705. Squaring the lme figures returns the lmer ones (\(0.77958^2 = 0.6077\)), so the two agree exactly and differ only in what they choose to print. The fixed intercept is 10.665 either way.

Note where the variance sits: between regions and between states, with almost none left within a state over time — the residual standard deviation of 0.157 is about a fifth of the state-level one. Most of the variation in this outcome is cross-sectional, not longitudinal.

Code
library(tidyverse)
library(haven)
library(dplyr)
library(readxl)
library(nlme)
library(lme4)
data <- read_dta('https://www.stata-press.com/data/r18/productivity.dta')
# lme4 for three level model
# (1|region) + (1|state) specifies CROSSED random effects; it numerically
# coincides with the intended nested structure here only because each
# state's label happens to be unique across the whole dataset (never reused
# across regions) -- verified: identical logLik to the explicitly nested
# (1|region/state) below. The nested form is the conceptually correct one
# and is robust even if state labels were ever reused across regions.
lmer1 <- lmer(gsp ~ 1 + (1|region/state), data=data)
summary(lmer1)
Linear mixed model fit by REML ['lmerMod']
Formula: gsp ~ 1 + (1 | region/state)
   Data: data

REML criterion at convergence: -400.9

Scaled residuals: 
    Min      1Q  Median      3Q     Max 
-2.8328 -0.6757  0.0474  0.6382  3.3928 

Random effects:
 Groups       Name        Variance Std.Dev.
 state:region (Intercept) 0.60775  0.7796  
 region       (Intercept) 0.50977  0.7140  
 Residual                 0.02466  0.1570  
Number of obs: 816, groups:  state:region, 48; region, 9

Fixed effects:
            Estimate Std. Error t value
(Intercept)   10.665      0.266    40.1
Code
lme1 <- lme(gsp ~ 1, random= list( region=~1, state=~1), data=data)
#or
#lme1 <- lme(gsp ~ 1, random= list(region = pdSymm(~1), state=pdSymm(~1)), data=data)
#but
#lme1 <- lme(gsp ~ 1, random= list( state=~1, region=~1), data=data)
#would be a different result!
#The other way to specify:
#lme2 <- lme(gsp ~ 1, random= ~ 1 | region/state, data=data)
summary(lme1)
Linear mixed-effects model fit by REML
  Data: data 
        AIC       BIC   logLik
  -392.8509 -374.0381 200.4254

Random effects:
 Formula: ~1 | region
        (Intercept)
StdDev:   0.7139792

 Formula: ~1 | state %in% region
        (Intercept)  Residual
StdDev:   0.7795814 0.1570457

Fixed effects:  gsp ~ 1 
               Value Std.Error  DF  t-value p-value
(Intercept) 10.66483 0.2659842 768 40.09574       0

Standardized Within-Group Residuals:
        Min          Q1         Med          Q3         Max 
-2.83282326 -0.67572390  0.04744387  0.63817953  3.39281358 

Number of Observations: 816
Number of Groups: 
           region state %in% region 
                9                48 

37.2 A growth model in R and stata

We implement a growth model in R and Stata, with time centred at 1970 and a correlated random intercept and slope for region. All four fits agree: mixed, menl, lmer and lme reach the same log likelihood, 888.824. The random slope on time is small (its variance is 0.000056), but it is estimated.

37.2.1 Stata

Code

* same growth model with mixed and menl
* Stata's "mixed ... || region: year" defaults to an INDEPENDENT covariance
* structure for region's random intercept and slope (var(year), var(_cons),
* cov=0 by construction) -- verified via `estat recovariance`. R's lmer
* "(year|region)" and lme's "region=~year" both default to an UNSTRUCTURED
* (correlated) covariance. Add covariance(unstructured) to match R, in both
* mixed and menl (menl's random effects are also independent by default).
* Time is centred at the first year, t = year - 1970, so the random intercept
* is the region's level in 1970 rather than an extrapolation to year 0.
webuse productivity, clear
gen t = year - 1970
mixed gsp t || region: t, covariance(unstructured) || state:
menl gsp =  {b2:} + {U1[region]}*t, define(b2: t U0[region]  U11[region>state]) covariance(U0 U1, unstructured)
(Public capital productivity)



Performing EM optimization ...

Performing gradient-based optimization: 
Iteration 0:  Log likelihood =  888.82273  
Iteration 1:  Log likelihood =  888.82404  
Iteration 2:  Log likelihood =  888.82404  

Computing standard errors ...

Mixed-effects ML regression                             Number of obs =    816

        Grouping information
        -------------------------------------------------------------
                        |     No. of       Observations per group
         Group variable |     groups    Minimum    Average    Maximum
        ----------------+--------------------------------------------
                 region |          9         51       90.7        136
                  state |         48         17       17.0         17
        -------------------------------------------------------------

                                                        Wald chi2(1)  = 107.46
Log likelihood =  888.82404                             Prob > chi2   = 0.0000

------------------------------------------------------------------------------
         gsp | Coefficient  Std. err.      z    P>|z|     [95% conf. interval]
-------------+----------------------------------------------------------------
           t |   .0263275   .0025397    10.37   0.000     .0213497    .0313053
       _cons |   10.43297   .2626235    39.73   0.000     9.918239     10.9477
------------------------------------------------------------------------------

------------------------------------------------------------------------------
  Random-effects parameters  |   Estimate   Std. err.     [95% conf. interval]
-----------------------------+------------------------------------------------
region: Unstructured         |
                      var(t) |    .000056   .0000274      .0000215     .000146
                  var(_cons) |   .4974817   .2974088      .1541361    1.605646
                cov(t,_cons) |  -.0045713   .0025218      -.009514    .0003714
-----------------------------+------------------------------------------------
state: Identity              |
                  var(_cons) |   .6121894   .1393574      .3918504     .956426
-----------------------------+------------------------------------------------
               var(Residual) |   .0039862   .0002046      .0036046    .0044081
------------------------------------------------------------------------------
LR test vs. linear model: chi2(4) = 4112.15               Prob > chi2 = 0.0000

Note: LR test is conservative and provided only for reference.


Obtaining starting values by EM:

Alternating PNLS/LME algorithm:

Iteration 1:  Linearization log likelihood =  888.82404
Iteration 2:  Linearization log likelihood =  888.82404

Computing standard errors:

Mixed-effects ML nonlinear regression           Number of obs     =        816

      Grouping information
      ------------------------------------------------------------------
                           |     No. of        Observations per group
                      Path |     groups    Minimum    Average    Maximum
      ---------------------+--------------------------------------------
                    region |          9         51       90.7        136
              region>state |         48         17       17.0         17
      ------------------------------------------------------------------

                                                Wald chi2(1)      =     107.20
Linearization log likelihood =  888.82404       Prob > chi2       =     0.0000

          b2: t U0[region] U11[region>state]

------------------------------------------------------------------------------
         gsp | Coefficient  Std. err.      z    P>|z|     [95% conf. interval]
-------------+----------------------------------------------------------------
b2           |
           t |   .0263275   .0025428    10.35   0.000     .0213436    .0313114
       _cons |   10.43297   .2629456    39.68   0.000     9.917608    10.94834
------------------------------------------------------------------------------

------------------------------------------------------------------------------
  Random-effects parameters  |   Estimate   Std. err.     [95% conf. interval]
-----------------------------+------------------------------------------------
region: Unstructured         |
                     var(U0) |     .49748   .2952832      .1554312    1.592257
                     var(U1) |    .000056   .0000274      .0000215    .0001459
                  cov(U0,U1) |  -.0045713   .0025207     -.0095118    .0003693
-----------------------------+------------------------------------------------
region>state: Identity       |
                    var(U11) |   .6121883   .1389459      .3923659     .955166
-----------------------------+------------------------------------------------
               var(Residual) |   .0039862   .0002046      .0036046    .0044081
------------------------------------------------------------------------------

37.2.2 R

Code
# lme4 for three level model, growth model
data$t <- data$year - 1970   # centre time at the first year, as in Stata
# state codes are unique across regions, so (1|state) is the nested state effect
lmer_growth1 <- lmer(gsp ~ 1 + t + (t|region) +  (1|state), data=data,  REML=FALSE,
                     control = lmerControl(optimizer = "bobyqa"))
summary(lmer_growth1)
Linear mixed model fit by maximum likelihood  ['lmerMod']
Formula: gsp ~ 1 + t + (t | region) + (1 | state)
   Data: data
Control: lmerControl(optimizer = "bobyqa")

      AIC       BIC    logLik -2*log(L)  df.resid 
  -1763.6   -1730.7     888.8   -1777.6       809 

Scaled residuals: 
    Min      1Q  Median      3Q     Max 
-3.9078 -0.5767  0.0122  0.5985  4.5440 

Random effects:
 Groups   Name        Variance  Std.Dev. Corr  
 state    (Intercept) 6.122e-01 0.782425       
 region   (Intercept) 4.975e-01 0.705317       
          t           5.598e-05 0.007482 -0.87 
 Residual             3.986e-03 0.063136       
Number of obs: 816, groups:  state, 48; region, 9

Fixed effects:
            Estimate Std. Error t value
(Intercept) 10.43297    0.26262   39.73
t            0.02633    0.00254   10.37

Correlation of Fixed Effects:
  (Intr)
t -0.766
Code
# nlme for three level model, growth model
#lme_growth1<-lme(gsp ~ year, random = list(region=pdSymm(~year), state=pdIdent(~1)),data=data, method="ML")
lme_growth1<-lme(gsp ~ t, random = list(region=~t, state=~1),data=data, method="ML")
summary(lme_growth1)
Linear mixed-effects model fit by maximum likelihood
  Data: data 
        AIC       BIC  logLik
  -1763.648 -1730.717 888.824

Random effects:
 Formula: ~t | region
 Structure: General positive-definite, Log-Cholesky parametrization
            StdDev      Corr  
(Intercept) 0.705322591 (Intr)
t           0.007482037 -0.866

 Formula: ~1 | state %in% region
        (Intercept)   Residual
StdDev:   0.7824247 0.06313614

Fixed effects:  gsp ~ t 
                Value  Std.Error  DF  t-value p-value
(Intercept) 10.432972 0.26294558 767 39.67730       0
t            0.026327 0.00254284 767 10.35357       0
 Correlation: 
  (Intr)
t -0.766

Standardized Within-Group Residuals:
        Min          Q1         Med          Q3         Max 
-3.90782851 -0.57667741  0.01216096  0.59852643  4.54401910 

Number of Observations: 816
Number of Groups: 
           region state %in% region 
                9                48 

37.3 CEM in R and Stata

“CEM” is a growth model with the residual being a exponential function of the time variable.

37.3.1 Stata

With raw calendar years (1970–1986) in the variance function, \(\exp(\gamma \cdot \text{year})\) is evaluated near year 2000 and the model does not converge. Centring time at 1970 fixes that.

Code

webuse productivity, clear
gen t = year - 1970

* residual variance sigma2 * exp(2 * gamma * t), with t centred at 1970
menl gsp =  {b2:} + {U1[region]}*t, define(b2: t U0[region]  U11[region>state]) covariance(U0 U1, unstructured) resvariance(exponential t) nolog
(Public capital productivity)



Mixed-effects ML nonlinear regression           Number of obs     =        816

      Grouping information
      ------------------------------------------------------------------
                           |     No. of        Observations per group
                      Path |     groups    Minimum    Average    Maximum
      ---------------------+--------------------------------------------
                    region |          9         51       90.7        136
              region>state |         48         17       17.0         17
      ------------------------------------------------------------------

                                                Wald chi2(1)      =      96.58
Linearization log likelihood =  908.40814       Prob > chi2       =     0.0000

          b2: t U0[region] U11[region>state]

------------------------------------------------------------------------------
         gsp | Coefficient  Std. err.      z    P>|z|     [95% conf. interval]
-------------+----------------------------------------------------------------
b2           |
           t |   .0273381   .0027818     9.83   0.000     .0218859    .0327904
       _cons |   10.43041   .2648885    39.38   0.000     9.911242    10.94959
------------------------------------------------------------------------------

------------------------------------------------------------------------------
  Random-effects parameters  |   Estimate   Std. err.     [95% conf. interval]
-----------------------------+------------------------------------------------
region: Unstructured         |
                     var(U0) |   .5064182   .3001106      .1585167    1.617869
                     var(U1) |   .0000675   .0000329       .000026    .0001753
                  cov(U0,U1) |  -.0047686   .0027319      -.010123    .0005858
-----------------------------+------------------------------------------------
region>state: Identity       |
                    var(U11) |   .6088354   .1384617      .3898694    .9507812
-----------------------------+------------------------------------------------
Residual variance:           |
  Exponential t              |
                      sigma2 |   .0015338     .00022      .0011579    .0020318
                       gamma |   .0556869   .0081777      .0396589    .0717148
------------------------------------------------------------------------------

37.3.2 R

With centred time, R and Stata agree.

Code
lme_growth1<-lme(gsp ~ t, random = list(region=pdSymm(~t), state=pdIdent(~1)),data=data, method="ML")
lme_growth2<-update(lme_growth1,weights=varExp( form = ~ t), method="ML", control = lmeControl(opt = "optim"))
summary(lme_growth2)
Linear mixed-effects model fit by maximum likelihood
  Data: data 
        AIC       BIC   logLik
  -1800.816 -1763.181 908.4081

Random effects:
 Formula: ~t | region
 Structure: General positive-definite
            StdDev      Corr  
(Intercept) 0.711318393 (Intr)
t           0.008217065 -0.816

 Formula: ~1 | state %in% region
        (Intercept)   Residual
StdDev:   0.7802004 0.03916322

Variance function:
 Structure: Exponential of variance covariate
 Formula: ~t 
 Parameter estimates:
     expon 
0.05569042 
Fixed effects:  gsp ~ t 
                Value  Std.Error  DF  t-value p-value
(Intercept) 10.430356 0.26478882 767 39.39123       0
t            0.027338 0.00278269 767  9.82436       0
 Correlation: 
  (Intr)
t -0.724

Standardized Within-Group Residuals:
        Min          Q1         Med          Q3         Max 
-3.63657023 -0.60788373  0.03464838  0.62215692  3.89628444 

Number of Observations: 816
Number of Groups: 
           region state %in% region 
                9                48 
Code
delta1<-lme_growth2$modelStruct$varStruct
delta1
Variance function structure of class varExp representing
     expon 
0.05569042 

37.4 Summary

Stata’s mixed and menl and R’s lme4 and nlme fit the same multilevel models with different syntax and different printed quantities. In the three-level random-intercept model for state productivity, lmer and lme agree exactly. One reports variances and the other standard deviations, and squaring the latter returns the former. Most of the variation lies between regions and between states, with little within a state over time.

The growth model and the consensus emergence model, a growth model whose residual variance changes exponentially over time, give the same answers in R and Stata once two things match: time is centred at the first year, and the random intercept and slope are allowed to correlate in every package (menl and mixed default to independent random effects, lmer and lme to correlated ones). Then all four growth fits reach a log likelihood of 888.824, and both emergence fits reach 908.408 with the same variance-function parameter, 0.0557. With raw calendar years the emergence model did not converge, and the packages disagreed.