[R-SIG-Mac] polynomial issue

Ivan Cabrera ivandiver2 at gmail.com
Sat Nov 6 00:05:08 CET 2010

Hi all, I'm new to any programming and I've been doing some stuff in R  
the last couple of month, I hope you can help me here…

I'm using lm() to do a 12 degree polynomial fit to a series of data  
x,y. Then I built a polynomial using the coefficients given by coef()  
function (replacing any NA by a 0), and evaluate it in x.

 > x<-data[,1]; y <- data[,2]
 > pol <- paste(paste("I(x",1:12,sep="^"),")",sep="")
 > form <- as.formula(paste("y~", paste(pol,collapse="+")))
 > p12 <- lm(form)
 > coef(p12)
   (Intercept)        I(x^1)        I(x^2)        I(x^3)         
I(x^4)        I(x^5)        I(x^6)        I(x^7)        I(x^8)         
I(x^9)       I(x^10)
  1.549683e+05 -2.801410e+02  2.238321e-01 -1.037342e-04  3.071376e-08  
-6.013217e-12  7.735856e-16 -6.168457e-20  2.493099e-24            NA  
       I(x^11)       I(x^12)
            NA  3.973316e-42
 > pl12 <- coef(p12)[1] + coef(p12)[2]*(x^1) + coef(p12)[3]*(x^2) +  
coef(p12)[4]*(x^3) + coef(p12)[5]*(x^4) + coef(p12)[6]*(x^5) +  
coef(p12)[7]*(x^6) + coef(p12)[8]*(x^7) + coef(p12)[9]*(x^8) +  
coef(p12)[11]*(x^10) + coef(p12)[13]*(x^12)

My problem comes when I replace the coef(p12)[ ] with their actual  
values. I get completely different values of the polynomial…

 > pl12.1 <- (1.549683e+05) + (-2.801410e+02)*(x^1) +  
(2.238321e-01)*(x^2) + (-1.037342e-04)*(x^3) + (3.071376e-08)*(x^4) +  
(-6.013217e-12)*(x^5) + (7.735856e-16)*(x^6) + (-6.168457e-20)*(x^7) +  
(2.493099e-24)*(x^8) + (-3.184072e-33)*(x^10) + (3.973316e-42)*(x^12)
 > rle(pl12==pl12.1)
Run Length Encoding
   lengths: int 3412
   values : logi FALSE

and not even the shape of the functions are alike when i plot them.

can anyone give me a clue of what's happening and how to fix it?


More information about the R-SIG-Mac mailing list