[R] Polynomial Fitting

Rolf Turner r.turner at auckland.ac.nz
Tue Sep 29 21:30:15 CEST 2009


On 30/09/2009, at 5:34 AM, chris carleton wrote:

>
> Thanks for the response. I'm sorry I didn't provide the code or  
> data example earlier. I was using the polynomial fitting technique  
> of this form;
>
> test <- lm(x[,34] ~ I(x[,1]) + I(x[,1]^2) + I(x[,1]^3))
>
> for the original fitting operation. I also tried to use;
>
> lm(y ~ poly(x,3,raw=TRUE))
>
> with the same results for the polynomial coefficients in both  
> cases. If my understanding is correct, both of the methods above  
> produce the coefficients of a polynomial based on the data in 'y'  
> as that data varies over 'x'. Therefore, I would assume that the  
> function of the polynomial should always produce the same results  
> as the predict() function in R produces. However, here are the raw  
> data for anyone that has the time to help me out.
>
> y:
> [1] 9097 9074 9043 8978 8912 8847 8814 8786 8752 8722 8686 8657  
> 8610 8604 8554
> [16] 8546 8496 8482 8479 8462 8460 8438 8428 8418 8384
>
> x:
> [1] 17.50    NA 20.59 21.43 17.78 21.89    NA 22.86    NA  6.10     
> NA  5.37
> [13]  3.80    NA  6.80    NA    NA    NA  5.80    NA    NA    NA     
> NA    NA
> [25]    NA
>
> I think that R lm() just ignores the NA values, but I've also tried  
> this by first eliminating NAs and the corresponding x values from  
> the data before fitting the poly and the result was the same  
> coefficients. Thanks very much to anyone who is willing to provide  
> information.

What's the problem?

fit <- lm(y~x+I(x^2)+I(x^3))
ccc <- coef(fit)
X <- cbind(1,x,x^2,x^3)
print(fitted(fit))
chk <- X%*%ccc
print(chk[!is.na(chk)])
print(range(fitted(fit)-chk[!is.na(chk)]))
[1] 0.000000e+00 5.456968e-12

The answers are the same.

	cheers,

		Rolf Turner

######################################################################
Attention:\ This e-mail message is privileged and confid...{{dropped:9}}




More information about the R-help mailing list