Search code examples
rsmoothing

how we can find a smooth function to our data?


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?


Solution

  • 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