How to include all possible two-way interaction terms in a linear model in R?

Viewed 28745

Is there an easy way to include all possible two-way interactions in a model in R?

Given this model:

lm(a~b+c+d)

What syntax would be used so that the model would include b, c, d, bc, bd, and cd as explanatory variables, were bc is the interaction term of main effects b and c.

1 Answers

You can write the following:

lm(a ~ (b + c + d)^2)

This creates all combinations of two-way interactions between b, c, and d

For example:

lm(mpg ~ (cyl+disp+hp)^2, data = mtcars)

gives:

Call:
lm(formula = mpg ~ (cyl + disp + hp)^2, data = mtcars)

Coefficients:
(Intercept)          cyl         disp           hp     cyl:disp       cyl:hp      disp:hp  
  5.601e+01   -4.427e+00   -1.184e-01   -1.142e-01    1.439e-02    1.556e-02   -8.567e-05
Related