# [R-sig-ME] Nested random effects in mgcv gam/bam

Mathew Guilfoyle mrgu|||oy|e @end|ng |rom gm@||@com
Mon Jun 24 14:33:51 CEST 2019

```I have a dataset comprising of subjects with a unique identifier ‘ID’ who are each in one of two groups ‘G’ .  I am looking to find the smooth relationship between numerical variables A and B that are both evaluated at multiple times in each subject.

Ignoring the grouping for the moment, a GAM formula including random intercept and ’slope’ for each subject would be:

m1 = bam(B ~ s(A, bs=‘cr’, k=10) + s(ID, bs=‘re’) + s(ID, A, bs=‘re’))

Now, I believe the smooth is different in each group therefore I want to obtain separate smooths based on G, and also include random intercepts and ‘slope’ for each subject but nested within each group.

Which of the following constructions is correct? (G is a factor)?:

m2a = bam(B ~ G + s(A, bs=‘cr’, k=10, by=G) + s(G, ID, bs=‘re’) + s(G, ID, A, bs=‘re’))

m2b = bam(B ~ G + s(A, bs=‘cr’, k=10, by=G) + s(ID, bs=‘re’, by=G) + s(ID, A, bs=‘re’, by=G))

I have tried do this more explicitly using gamm:

m3 = gamm(B ~ G + s(A, bs=‘cr’, k=10, by=G), random = list(G=~1+A, ID=~1+A))

but this takes a lot longer (hours) to run given the size of the dataset and as I don’t need/want to specify the correlation structure of the random effects I hoped that one of the bam calls above was equivalent.  I have tried the various models on a subset of the data and model m2a gives qualitatively very similar smooths to model m3.

Thanks.
```