How to fit a repeated measure GAM model with mgcv? We are hoping for some guidance regarding a gam model using mgcv R package. We want to know if variables measured over time affect our outcome variable. In other words if variable "X" and/or variable "Y" changes after controlling for time.
We have the following variables:

*

*ID - subject identification

*year - continuous covariate, repeated measures

*Var X - continuous variable

*Var Y - continuous variable

*Outcome - continuous variable, dependent variable

We are not entirely sure if the following model answers our question:
m1 <- gam(Outcome ~ s(VarX) + s(VarY) + s(year) +
      s(year, ID, bs = "fs"),
      family = gaussian, data = dat, method = 'REML')

Or if the model below is the one taking into account that each variable is measured over time for each ID:
m2 <- gam(Outcome ~ s(VarX) + s(VarY) + s(year) +
     s(year, ID, bs = "fs", by = VarX) +
     s(year, ID, bs = "fs", by = VarY),
     data = dat, method = 'REML')

 A: Maybe something like this?
m2 <- gam(Outcome ~ s(VarX) + s(VarY) + s(year) +
     s(VarX, ID, bs = "fs") +
     s(VarY, ID, bs = "fs"),
     data = dat, method = 'REML')

This is similar to a random slope and intercept model with a statistical control for year at the global level. If you were to include the interaction between VarX/VarY and year, then you would want to fit it using a tensor product rather than an isotropic smoother (te() rather than s()). However, the factor smooth interaction won't work for te smooths. Pedersen et al. 2019 has a general form for fitting these higher dimensional models:
y ~ te(x1, x2, bs = "tp", m = 2) +
    t2(x1, x2, fac, bs = c("tp","tp","re"), m = 2, full = TRUE)

where x1/x2 are continuous covariates and fac is your grouping variable. The tensor product smooth allows for modeling interactions among covariates with different units, whereas the isotropic smoothers work best when modeling covariates with the same units (commonly units of distance).
References:
Pedersen, Eric J., et al. "Hierarchical generalized additive models in ecology: an introduction with mgcv." PeerJ 7 (2019): e6876.
