5
votes

I am trying to specify both a random intercept and random slope term in a GAMM model with one fixed effect.

I have successfully fitted a model with a random intercept using the below code within the mgcv library, but can now not determine what the syntax is for a random slope within the gamm() function:

M1  = gamm(dur ~ s(dep, bs="ts", k = 4), random= list(fInd = ~1), data= df)

If I was using both a random intercept and slope within a linear mixed-effects model I would write it in the following way:

M2 = lme(dur ~ dep, random=~1 + dep|fInd, data=df)

The gamm() supporting documentation states that the random terms need to be given in the list form as in lme() but I cannot find any interpretable examples that include both slope and intercept terms. Any advice / solutions would be much appreciated.

2
Do you mean random slope or random intercept? If random slope, I'm pretty sure you need to specify which variable(s) the random slope applies to.MrFlick
Both. I want to use both a random slope and random intercept for the factor variable fInd (as shown in the lme() example), I just can't figure out the syntax.jjulip

2 Answers

6
votes

The gamm4 function in the gamm4 package contains a way to do this. You specify the random intercept and slope in the same way that you do in the lmer style. In your case:

M1 = gamm4(dur~s(dep,bs="ts",k=4), random = ~(1+dep|fInd), data=df)

Here is the gamm4 documentation: https://cran.r-project.org/web/packages/gamm4/gamm4.pdf

3
votes

Here is the gamm() syntax to enter correlated random intercept and slope effects, using the sleepstudy dataset.

library(nlme)
library(mgcv)
data(sleepstudy,package='lme4')

# Model via lme()
fm1 <- lme(Reaction ~ Days, random= ~1+Days|Subject, data=sleepstudy, method='REML')
# Model via gamm()
fm1.gamm <- gamm(Reaction ~ Days, random= list(Subject=~1+Days), data=sleepstudy, method='REML')

VarCorr(fm1)
VarCorr(fm1.gamm$lme)
# Both are identical
# Subject = pdLogChol(1 + Days) 
#             Variance StdDev    Corr  
# (Intercept) 612.0795 24.740241 (Intr)
# Days         35.0713  5.922103 0.066 
# Residual    654.9424 25.591843  

The syntax to enter uncorrelated random intercept and slope effects is the same for lme() and gamm().

# Model via lme()
fm2 <- lme(Reaction ~ Days, random= list(Subject=~1, Subject=~0+Days), data=sleepstudy, method='REML')
# Model via gamm()
fm2.gamm <- gamm(Reaction ~ Days, random= list(Subject=~1, Subject=~0+Days), data=sleepstudy, method='REML')

VarCorr(fm2)
VarCorr(fm2.gamm$lme)
# Both are identical
#             Variance            StdDev   
# Subject =   pdLogChol(1)                 
# (Intercept) 627.5690            25.051328
# Subject =   pdLogChol(0 + Days)          
# Days         35.8582             5.988172
# Residual    653.5838            25.565285

This answer also shows how to enter multiple random effects into lme().