---
title: "Doing the same multi-level model with R and Stata"
date: "2023-10-26"
---
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-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.
```{r}
#| label: setup
#| include: false
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
#| label: libs
#| include: false
# Attach packages HERE, in an uncached chunk, rather than inside the
# `cache: true` chunk below. A cached chunk restores its *objects* on replay but
# does not re-run its `library()` calls, so the later uncached CEM chunk could not
# find nlme::lme and the whole CEM section rendered as
# "could not find function \"lme\"" errors.
library(tidyverse)
library(haven)
library(dplyr)
library(readxl)
library(nlme)
library(lme4)
```
## 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).
### Stata
```{r}
#| include: false
library(Statamarkdown)
stataexe <- find_stata()
#stataexe <- "/usr/local/bin/stata"
knitr::opts_chunk$set(engine.path=list(stata=stataexe))
```
```{stata}
*| label: stata1
*| echo: true
*| collectcode: true
* 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])
```
### 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.
```{r}
#| label: r1
#| echo: true
#| cache: true
#| collectcode: true
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)
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)
```
## 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.
### Stata
```{stata}
*| label: stata2
*| echo: true
*| collectcode: true
* 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)
```
### R
```{r}
#| label: r2
#| echo: true
#| cache: true
#| collectcode: true
# 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)
# 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)
```
## CEM in R and Stata
"CEM" is a growth model with the residual being a exponential function of the time variable.
### 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.
```{stata}
*| label: stata3
*| echo: true
*| collectcode: true
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
```
### R
With centred time, R and Stata agree.
```{r}
#| label: cem1
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)
delta1<-lme_growth2$modelStruct$varStruct
delta1
```
## 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.