I want to do a polynomial regression in R with one dependent variable y
and two independent variables x1
and x2
. In my mind the model should look as follows,
y=b0 + b1x1+ b2x2+ b3x1^2+ b4x2^2+ b5x1x2
I tried lm(y~x1+x2+poly(x1,2,raw=TRUE)+poly(x2,2,raw=TRUE))
and also lm(y~x1+x2+I(x1^2)+I(x2^2))
. But this only gives the squares and not the product of the two variables.
I can of cause do lm(y~x1+ x2+ x1^2+ x2^2+ x1x2)
. But i would like to know whether there is a much easier way than to write the whole equation out. I also would like to do to the power of 3 and 4 models which is more lengthy.
The simple linear regression equation can be adapted to accommodate multiple dependent variables in the following way: Theoretically there is no limit to the number of independent variables that can be analysed, but within the spreadsheet the maximum is 75.
Performing multivariate multiple regression in R requires wrapping the multiple responses in the cbind() function. cbind() takes two vectors, or columns, and “binds” them together into two columns of data. We insert that on the left side of the formula operator: ~. On the other side we add our predictors.
you can use polym
y ~ polym(x1, x2, degree=2, raw=TRUE) # is equivalent to
y ~ x1 + x2 + I(x1^2) + I(x2^2) + x1:x2
But be careful with the order of the coefficients they are not the same as the second formula.
If you use degree=3 then it will add interactions of higher order like this I(x1^2):x2 +I(x2^2):x1, thus you have to adapt your formula.
NB : polym is a wrapper for poly, so you can use this latter with the same call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With