data(spdg, package = "cpr")
## Extract the control polygon and spline for plotting. We'll use base R
## graphics for this example.
a_cp <- cp(pdg ~ bsplines(day, df = 10, bknots = c(-1, 1)), data = spdg)
spline <- get_spline(a_cp)
plot(spline$x, spline$y, type = "l")
# compare to the plot.cpr_cp method
plot(a_cp, show_spline = TRUE)
# derivatives
f0 <- function(x) {
#(x + 2) * (x - 1) * (x - 3)
x^3 - 2 * x^2 - 5 * x + 6
}
f1 <- function(x) {
3 * x^2 - 4 * x - 5
}
f2 <- function(x) {
6 * x - 4
}
x <- sort(runif(n = 100, min = -3, max = 5))
bknots = c(-3, 5)
bmat <- bsplines(x, bknots = bknots)
theta <- coef(lm(f0(x) ~ bsplines(x, bknots = bknots) + 0) )
cp0 <- cp(bmat, theta)
spline0 <- get_spline(cp0, derivative = 0)
spline1 <- get_spline(cp0, derivative = 1)
spline2 <- get_spline(cp0, derivative = 2)
old_par <- par()
par(mfrow = c(1, 3))
plot(x, f0(x), type = "l", main = "spline")
points(spline0$x, spline0$y, pch = 2, col = 'blue')
plot(x, f1(x), type = "l", main = "first derivative")
points(spline1$x, spline1$y, pch = 2, col = 'blue')
plot(x, f2(x), type = "l", main = "second derivative")
points(spline2$x, spline2$y, pch = 2, col = 'blue')
par(old_par)
Run the code above in your browser using DataLab