John Tillinghast
2009-Dec-21 18:20 UTC
[R] mgcv with discrete covariates, interaction term
I'm trying to build a model with an overall smooth function for all the data, plus an additional smooth function for *some* of the data. If "ind" is my indicator variable (0 for some x, 1 for others), I imagined I could write it like this: gam.obj <- gam(y ~ s(x) + ind*s(x)) but this does not work. Does mgcv have a way of doing this? If not directly, is there a reasonable workaround?
On Mon, 2009-12-21 at 13:20 -0500, John Tillinghast wrote:> I'm trying to build a model with an overall smooth function for all > the data, plus an additional smooth function for *some* of the data. > If "ind" is my indicator variable (0 for some x, 1 for others), I > imagined I could write it like this: > > gam.obj <- gam(y ~ s(x) + ind*s(x)) > > but this does not work. > > Does mgcv have a way of doing this? If not directly, is there a > reasonable workaround? >If I understand you correctly, yes. see ?s and argument 'by'. Something like: ## some dummy data dat <- data.frame(y=rnorm(100), x=c(rnorm(50,5), rnorm(50)), ind = rep(c(1,0), each = 50)) ## fit model mod <- gam(y ~ s(x) + s(x, by = ind), data = dat) This works when ind is a simple indicator, but if you have more levels (as a factor), by = ind will fit a separate smooth to each level of ind. HTH G -- %~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~% Dr. Gavin Simpson [t] +44 (0)20 7679 0522 ECRC, UCL Geography, [f] +44 (0)20 7679 0565 Pearson Building, [e] gavin.simpsonATNOSPAMucl.ac.uk Gower Street, London [w] http://www.ucl.ac.uk/~ucfagls/ UK. WC1E 6BT. [w] http://www.freshwaters.org.uk %~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%