Linear mixed models: several nested random effects

122 views
Skip to first unread message

Serge-Étienne Parent

unread,
Nov 8, 2017, 7:28:11 AM11/8/17
to pystatsmodels
Hi,

I'm trying to create a linear mixed model with nested random effects. Kerby Sheddon proposed an interesting structure to include one variable nested in another. But I can't figure out how to play with this structure to fit my needs. In particular, what should be specified in re_formula and what mean the zero and the C() in {'subject' : '0 + C(subject)'}. In the end, I would like to do in Python like I would do in R:

library(nlme)
data = read.csv('http://bit.ly/2hPKDtM')
mlm = lme(Weight ~ Dose,
          random = ~ 1 + 1|Year/Site/Block,
          data=data)

In Python?

import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf

data = pd.read_csv('http://bit.ly/2hPKDtM', index_col=0)

mlm = smf.mixedlm("Weight ~ Dose", 
                  groups="Year",
                  re_formula="1", 
                  vc_formula={"Site": "0+C(Site)", "Block": "0+C(Block)"},
                  data=data).fit()

Thanks!

Serge-Étienne Parent

unread,
Nov 14, 2017, 4:51:41 PM11/14/17
to pystatsmodels
I finally got it. I had to create columns for nested effects...

data['Year_Site'] = date['Year'].astype(str) + "_" + data['Site'].astype(str)
data['Year_Site_Block'] = date['Year'].astype(str) + "_" + data['Site'].astype(str) + data['Block'].astype(str)

... then add the new columns as random intercepts.

mlm = smf.mixedlm("Weight ~ Dose", 
                  groups="Year",
                  re_formula="1", 
                  vc_formula={"Year_Site": "0+C(Year_Site)", "Year_Site_Block": "0+C(Year_Site_Block)"},
                  data=data).fit()
Reply all
Reply to author
Forward
0 new messages