I am trying to estimate the 1st derivative of my bspline fitting. I used spline2 R package and the code and results are included below.
require(splines2)
x = seq(0,10,by=0.1)
y = x^3+x^2+2*x+1
y_der = 3*(x^2)+2*x+2 # Manually calculated true derivative
mod <- lm(y ~ bSpline(x, knots = quantile(x, probs = seq(0, 1, 0.25)), degree = 3L, intercept = TRUE))
pdat <- data.frame(x = seq(min(x), max(x), length = 100))
yhat = predict(mod, newdata = pdat)
## Plot
plot(y ~ x)
lines(y_der ~ x, lwd = 2, col = "blue")
lines(yhat ~ x, data = pdat, lwd = 5, col = "green")
mod_der <- lm(y ~ bSpline(x, knots = quantile(x, probs = seq(0, 1, 0.25)), degree = 3L, deriv = 1L, intercept = TRUE))
yhat_der = predict(mod_der, newdata = pdat)
lines(yhat_der ~ x, data = pdat, lwd = 2, col = "red")
Graph: The derivative curve seems to be identical to the bspline fit
The green curve of bspline estimate almost perfectly fits the y=f(x) function. However the red curve of 1st derivative seems identical to the green curve, which is not what I expected. I thought it was somewhere near the blue parabola.
I understand that my R variable mod keeps the fitted bspline model. If I want to estimate the y value corresponds to a new x, I can just do predict(mod, data...). And I thought I just need to do the same thing if I want to estimate the derivative. But that doesn't work.
How can I get the model of 1st derivative of bspline fitting?