Evaluate smooth.spline at specific point in R

528 Views Asked by At

In R, I'm using smooth.spline {stats} function to fit a spline through some function values.

x=seq(0, 1,0.01)
y=sin(x*23) - 0.6*cos(x*7)
plot(x,y)
ss= smooth.spline(x=x, y=y, df=35)
plot(ss)

Now ss object contains all the values of the fitted spline required to draw and evaluate the spline at any given point.

ss$fit
$knot
[1] 0.0000000 0.0000000 0.0000000 0.0000000 0.3333333 0.6666667 1.0000000 1.0000000 1.0000000    1.0000000

$nk
[1] 6

$min
[1] 1

$range
[1] 3

$coef
[1] 0.5549946 0.4366268 0.1988102 1.1388495 0.7444880 0.5479000

attr(,"class")
[1] "smooth.spline.fit" 

How can I use the coefficients and knots from the ss$fit object to compute the value of the spline function at a point xa. I know I can use predict but I would like to actually compute the value manually.

My attempt is described in the following function which is not producing the expected results:

estimateSpline <- function(xv, fit){
    knots = unique(fit$knot)
    knots = knots[ 2 : (length(knots)-1) ]
    len = length(knots)

    xv = (xv - fit$min) / fit$range

    Gbase = rep(xv, len )
    Gbase = Gbase - knots
    Gbase[Gbase < 0] = 0
    Gbase = c(rep(xv,4), Gbase)

    Gpow = c(seq(0, 3, 1), rep (3, len))
    Gvec = Gbase ^ Gpow
    res = fit$coef %*% Gvec
    return (res)
}

I understand the theory behind splines and I read a lot of documents about the math behind it.

Can anyone help me evaluate the value of the fitted spline function at any arbitrary point xv?

I don't fully comprehend the data format, number and order of the parameters outputted by smooth.spline so that I can reconstruct the predict function's results.

Thanks

0

There are 0 best solutions below