Search code examples
rinterpolationcubic-spline

View interpolated values of cubic spline (R)


I want to perform cubic spline interpolation :

x <- c(1,1.5, 2, 4,5,6,7,8,9,10,12,15,20, 25,30)
y <- c(-0.402, -0.303, -0.198, 0.211,0.4133,0.606,0.7835,0.9404,1.0733,1.189,1.383,1.594,1.812,1.893,1.922)

smooth.spline (x,y) 

you can notice that in the x vector , the x-value of 3 needs to be interpolated. How can I view interpolated values ( or insert an x values and get the interpolated y value), and view the spline functions?


Solution

  • You can use predict to apply the fitted spline function:

    > x <- c(1,1.5, 2, 4,5,6,7,8,9,10,12,15,20, 25,30)
    > y <- c(-0.402, -0.303, -0.198, 0.211,0.4133,0.606,0.7835,0.9404,1.0733,1.189,1.383,1.594,1.812,1.893,1.922)
    > predict(smooth.spline (x,y), 3)
    $x
    [1] 3
    
    $y
    [1] 0.006938673
    

    Some more information on the spline functions you can get using str function:

    > str(smooth.spline(x,y))
    List of 19
     $ x         : num [1:15] 1 1.5 2 4 5 6 7 8 9 10 ...
     $ y         : num [1:15] -0.403 -0.301 -0.199 0.212 0.413 ...
     $ w         : num [1:15] 1 1 1 1 1 1 1 1 1 1 ...
     $ yin       : num [1:15] -0.402 -0.303 -0.198 0.211 0.413 ...
     $ tol       : num 9e-06
     $ data      :List of 3
      ..$ x: num [1:15] 1 1.5 2 4 5 6 7 8 9 10 ...
      ..$ y: num [1:15] -0.402 -0.303 -0.198 0.211 0.413 ...
      ..$ w: num 1
     $ no.weights: logi TRUE
     $ lev       : num [1:15] 0.766 0.392 0.592 0.708 0.572 ...
     $ cv.crit   : num 6.3e-06
     $ pen.crit  : num 7.17e-06
     $ crit      : num 6.3e-06
     $ df        : num 10.9
     $ spar      : num 0.336
     $ ratio     : num 5.29e-06
     $ lambda    : num 5.51e-06
     $ iparms    : Named int [1:5] 1 0 13 0 NA
      ..- attr(*, "names")= chr [1:5] "icrit" "ispar" "iter" "" ...
     $ auxM      : NULL
     $ fit       :List of 5
      ..$ knot : num [1:21] 0 0 0 0 0.0172 ...
      ..$ nk   : int 17
      ..$ min  : num 1
      ..$ range: num 29
      ..$ coef : num [1:17] -0.403 -0.369 -0.301 -0.096 0.145 ...
      ..- attr(*, "class")= chr "smooth.spline.fit"
     $ call      : language smooth.spline(x = x, y = y)
     - attr(*, "class")= chr "smooth.spline"