Reputation:
I want to fit a model $Y = X_1^2 + X_2^2 + X_1 + X_2 + X_1\cdot X_2$
How to build this in R
glm(Y ~ poly(X1,2) * poly(X2,2)
how to generalise it to higher order ? eg. $Y = X_1^3 + X_2^3 + X_1\cdot X_2^2 + X_1^2 \cdot X_2 + X_1^2 + X_2^2 + X_1 + X_2 + X_1\cdot X_2$
Upvotes: 0
Views: 1051
Reputation: 81713
You can use glm
with the following formula:
glm(Y ~ poly(X1, 2) + poly(X2, 2) + X1:X2)
The function poly
creates polynomials. In your example, poly(X1, 2)
results in $X_1$ and $X_1^2$. Note that poly
creates orthogonal polynomials. If you want raw polynomials, you have to use the argument raw = TRUE
.
The term X1:X2
is the interaction between $X_1$ and $X_2$, i.e., $X_1 \cdot X_2$.
Furthermore, your formula doesn't contain an intercept. I suppose this was not intended. However, you you really want to create a model without an intercept in R, you have to change the command to glm(Y ~ 0 + poly(X1, 2) + poly(X2, 2) + X1:X2)
.
Note that unless you specify a family
in glm
, the function will fit a linear model.
The formula you proposed (Y ~ poly(X1,2) * poly(X2,2)
) creates all the terms of the formula above and additional terms, namely all interactions between the polynomials of first and second order of $X_1$, and $X_2$, i.e., $X_1 \cdot X_2^2$, $X_1^2 \cdot X_2$, and $X_1^2 \cdot X_2^2$.
Upvotes: 1