Skip to content

How to find the derivative of bspline fit in R by using splines2 #10

Answered by wenjie2wang
CourseraXRay asked this question in Q&A
Discussion options

You must be logged in to vote

@CourseraXRay See the following code chunk for the revised example:

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

mat <- bSpline(x, df = 6, degree = 3L, intercept = TRUE)
mod <- lm(y ~ mat - 1)

## given new x
new_x <- seq(min(x), max(x), length.out = 1e3)
pmat <- predict(mat, new_x)
pmat_der <- deriv(pmat)
yhat <- c(pmat %*% coef(mod))
yhat_der <- c(pmat_der %*% coef(mod))

## Plot
plot(y ~ x)
points(y_der ~ x, lwd = 2, col = "blue")
lines(yhat ~ new_x, lwd = 5, col = "green")
lines(yhat_der ~ new_x, lwd = 2, col = "red")

There are several things that you need to be aware of.

  • There is no derivs argument for bSpli…

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by CourseraXRay
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants