-2

Suppose I have this small data T

 69 59 100 70 35 1

 matplot(t(T[1,]), type="l",xaxt="n")

enter image description here

I want find a polynomial which is fit to data. (even over fit is ok) is there any way that I can do it in R?

1 Answers1

1

First the data.

y <- scan(text = '69 59 100 70 35 1')
x <- seq_along(y)

Now a 2nd degree polynomial fit. This is fit with lm.

fit <- lm(y ~ poly(x, 2))
summary(fit)
#
#Call:
#lm(formula = y ~ poly(x, 2))
#
#Residuals:
#       1        2        3        4        5        6 
#  7.0000 -20.6571  17.8286   0.4571  -6.7714   2.1429 
#
#Coefficients:
#            Estimate Std. Error t value Pr(>|t|)   
#(Intercept)   55.667      6.848   8.128  0.00389 **
#poly(x, 2)1  -52.829     16.775  -3.149  0.05130 . 
#poly(x, 2)2  -46.262     16.775  -2.758  0.07028 . 
#---
#Signif. codes:  
#0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
#
#Residual standard error: 16.78 on 3 degrees of freedom
#Multiple R-squared:  0.8538,   Adjusted R-squared:  0.7564 
#F-statistic: 8.761 on 2 and 3 DF,  p-value: 0.05589

Finally, the plot of both the original data and of the fitted values.

newy <- predict(fit, data.frame(x))

plot(y, type = "b")
lines(x, newy, col = "red")

enter image description here

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
  • thank you, now I have to play with it to get a better graph? –  Jun 09 '19 at 20:37
  • @user9272398 I don't find it a bad graph, it's a statistic fit, not a [Lagrange polynomial](https://en.wikipedia.org/wiki/Lagrange_polynomial). – Rui Barradas Jun 09 '19 at 20:44
  • with lm(y ~ poly(x, 5)) it is verrrrry good, I have one more question: if I want to write down this polynomial the coefficient are for x,x2,x3,x4,x5? there is no x1x2 or somwthing like that? becouse for lm(y ~ poly(x, 5)) I just have 5 coefficients. thanks again you helped me alot –  Jun 09 '19 at 21:06
  • in other words what is 5? the order of polynomial? –  Jun 09 '19 at 21:26
  • 1
    @user9272398 Yes, 5 is the order of the polynomial. And no, there is no `x1x2` because those are powers of the very same `x`. Note that you have 6 data points in the example, so that polynomial of degree `6 - 1 == 5` is a perfect fit and there are no degrees of freedom left. Not a good choice, just check out `summary(lm(y ~ poly(x, 5)))`. – Rui Barradas Jun 09 '19 at 21:41
  • well, I need it for a special case where over fitting is ok, so it works for me. now I ave 800 rows and for each of them I want to find fitted polynomial. should I do that row by row or there is a easier way to do that? –  Jun 09 '19 at 21:50