Fitting orthogonal polynomials in model

573 views Asked by At

I would like to fit orthogonal polynomials in my model. As of now, I am first getting the orthogonal polynomials by using something like this: contr.poly(11)

I then create a new variable for the linear, quadratic, etc. that I can then include in the model: lm(y~x+p+p_linear, data=d,...)

Is there a faster way to fit orthogonal polynomials in a formula?

An example would be: lm(y~x+p+I((p - mean(p)/sqrt(440))

I would like to fit each orthogonal polynomials term individually (linear first, then linear+quadratic, etc)

TIA.

Update:

data(mtcars)
mtcars$carb <- factor(mtcars$carb)
contrasts(mtcars$carb) <- contr.poly(n=levels(mtcars$carb))
contrasts(mtcars$carb)

mt.mod <- lm(mpg ~ carb, data=mtcars)
summary(mt.mod)

How can I fit the orthogonal polynomials step-by-step; first carb.L, then carb.L+carb.Q, and then carb.L+carb.Q+carb.C

1

There are 1 answers

0
IRTFM On

This uses the C function to construct polynomial contrasts of a factor variable in increasing degree. The bquote function with its helper .() function are used to substitute a degree-value into a language object,

sapply(1:3, function(degr){ 
                 form <- as.formula( bquote(mpg ~ C(factor(carb), poly, .(degr)))); 
                 coef( lm(form, data=mtcars))})
[[1]]
               (Intercept) C(factor(carb), poly, 1).L 
                  18.01040                  -11.13885 

[[2]]
               (Intercept) C(factor(carb), poly, 2).L 
                 18.821460                  -8.382298 
C(factor(carb), poly, 2).Q 
                  3.777842 

[[3]]
               (Intercept) C(factor(carb), poly, 3).L 
                18.9100420                 -7.9958797 
C(factor(carb), poly, 3).Q C(factor(carb), poly, 3).C 
                 4.0995446                  0.7565959 

I (re-)discovered that this approach had already read been posted to Rhelp back in 2008 following some prompting by the ever helpful Prof Ripley http://markmail.org/message/jz56m5gztqowa4lp?q=list:org%2Er-project%2Er-help+from:%22David+Winsemius%22+contrasts+poly