Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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.

like image 951
Boris Kris Avatar asked Nov 06 '17 19:11

Boris Kris


People also ask

How do you add interaction variables in R?

A two step process can be followed to create an interaction variable in R. First, the input variables must be centered to mitigate multicollinearity. Second, these variables must be multiplied to create the interaction variable.

Can you have multiple interaction terms in regression?

First, it is possible to have multiple interaction terms in a model. Second, people may ask why you included some interaction terms and not others - you need to have a good answer.

How do you find the interaction between two variables?

To understand potential interaction effects, compare the lines from the interaction plot: If the lines are parallel, there is no interaction. If the lines are not parallel, there is an interaction.


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 
like image 100
acylam Avatar answered Oct 20 '22 06:10

acylam