mgcv: how to specify interaction between smooth and factor?

后端 未结 1 362
星月不相逢
星月不相逢 2021-01-03 03:12

In R, I would like to fit a gam model with categorical variables. I thought I could do it like with (cat is the categorical variable).

lm(data = df, formula          


        
1条回答
  •  孤城傲影
    2021-01-03 03:43

    One of the comments has more or less told you how. Use by variable:

    s(x1, by = cat)
    

    This creates the "factor smooth" smoothing class fs, where a smooth function of x1 is created for each factor level. Smoothing parameters are also duplicated but not linked, so they are estimated indecently. You can set

    s(x1, by = cat, id = 0)
    

    to use a single smoothing parameter for all "sub smooths".

    Also note that contrast does not apply to factor but smooth function is still subject to centering constraint. What this means is that you need to specify factor variable as a fixed effect, too:

    s(x1, by = cat) + cat
    

    0 讨论(0)
提交回复
热议问题