Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formula for all first and second order predictors including interactions in R

Tags:

r

formula

In the statistics programming language R, the following formula (e.g. in lm() or glm())

z ~ (x+y)^2  

is equivalent to

z ~ x + y + x:y

Assuming, I only have continuous predictors, is there a concise way to obtain

z ~ I(x^2) + I(y^2) + I(x) + I(y) + I(x*y)

A formula that does the right thing for factor predictors is a plus.

One possible solution is

z ~ (poly(x,2) + poly(y,2))^2

I am looking for something more elegant.

like image 433
chris Avatar asked Sep 07 '10 17:09

chris


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.

How do you find interactions in a linear regression?

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.

What is 2nd order interaction?

in analysis of variance or regression analysis, an effect in which three independent variables combine to have a nonadditive influence on a dependent variable.


1 Answers

I don't know if it is more elegant or not, but the poly function can take multiple vectors:

z ~ poly(x, y, degree=2)

This will create all the combinations that you asked for, without additional ones. Do note that you need to specify degree=2, not just 2 when doing it this way.

like image 159
Greg Snow Avatar answered Sep 26 '22 07:09

Greg Snow