Isolating coefficients from polynomial fit in r

2019-07-30 10:11发布

问题:

I have fitted a simple 2nd order polynomial to time series data in the following form:

polyfit <- lm(y ~ poly(x,2))

I wish to extract the respective coefficients (A, B and C) from the fitted polynomial of the form y = Ax^2 + Bx + C. I naturally thought the answer would be found in polyfit$coefficients within the polyfit object but these coefficients are not correct. I have tried some very simple data sets and compared with excel and whilst the poly curve fits are identical in R and excel, the A,B and C coefficints obtained from excel are correct but those obtained from the polyfit object arent? Have I extracted the incorrect information from the polyfit object? It would be more convenient for me to extract the coefficients directly from R for my purposes? Can anyone help?

回答1:

By default poly fits orthogonal polynomials. Essentially it uses the following ideas...

x <- 1:10

# in this case same as x-mean(x)
y1 <- residuals(lm(x ~ 1)) 
# normalize to have unit norm
y1 <- y1/sqrt(sum(y1^2))

y2 <- residuals(lm(y1^2 ~ y1))
y2 <- y2/sqrt(sum(y2^2))

y3 <- residuals(lm(x^3 ~ y2 + y1))
y3 <- y3/sqrt(sum(y3^2))

cbind(y1, y2, y3)    
poly(x, 3)

to construct a set of orthonormal vectors that still produce the same predictions. If you just want to get a polynomial in the regular way then you want to specify raw=TRUE as a parameter.

y <- rnorm(20)
x <- 1:20
o <- lm(y ~ poly(x, 2, raw = TRUE))
# alternatively do it 'by hand'
o.byhand <- lm(y ~ x + I(x^2))