[R] mgcv with discrete covariates, interaction term

Gavin Simpson gavin.simpson at ucl.ac.uk
Tue Dec 22 10:11:19 CET 2009


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
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%




More information about the R-help mailing list