syntax of gam longitudinal dataset I would like to have some help on gam syntax in R. My question includes whether I am thinking about an appropriate model.
I have a longitudinal data-set in which participants can have a different number of follow-ups, so from 1 to 3 observation variables (brain region volume) are available for each participant. I would like to check the effect of age on this observation variable and because I have some reasons to believe that the relationship between my two variables isn't linear, I took interest in generalized additive models. So far, I built this model
gam(data = df.data, obs ~ s(age) + gender + education + s(subject, age, bs = "re"), method = "REML")
but I am not sure if this is a good way to model the cross-sectional and longitudinal effect of age on my variable of interest. Especially is this s(subject, age, bs = "re")  the way to model a random slope for each participant and does that makes sense?
 A: Your model:
gam(data = df.data, obs ~ s(age) + gender + education + s(subject, age, bs = "re"), 
    method = "REML")

would specify a global smooth of age, plus random slopes (i.e. linear effects) of age by subjects. You might want to add random intercepts to that model also: + s(subject, bs = 're').
If you assume the age effect is non-linear, you might want to use random smooths of age in your model. Then you have a couple of options


*

*do you want a global smoother?

*do you want each random smooth to have the same smoothness parameter (wiggliness)?


Colleagues and I outlined these models in detail in a recent paper (Pedersen et al 2019). Briefly, not covering all options, you could have random smooths via:
gam(obs ~ gender + education + s(age, subject, bs = "fs"), 
    data = df.data, method = "REML")

wherein all the subject specific smooths of age share the same degree of wiggliness (the same smoothness parameter). A global smooth plus random smooths would be given by
gam(obs ~ gender + education + s(age) + s(age, subject, bs = "fs"), 
    data = df.data, method = "REML")

If you want each subject to have different smoothness parameters (different wigglinesses) then two models above might become:
gam(obs ~ subject + gender + education + s(age, by = subject), 
    data = df.data, method = "REML")

and
gam(obs ~ subject + gender + education + s(age) + s(age, by = subject, m = 1), 
    data = df.data, method = "REML")

where I have added a fixed, parametric subject effect as factor by smooths are centred about the model intercept. And in the second by model I added m = 1 so that we penalised deviations from the global smooth.
Which you want will depend on how you want to model the smooth effects. If you want to predict for subjects not in the data set, then you'll need a global smooth, for example.
References
Pedersen, E.J., Miller, D.L., Simpson, G.L., Ross, N., 2019. Hierarchical generalized additive models in ecology: an introduction with mgcv. PeerJ 7, e6876. https://doi.org/10.7717/peerj.6876
