9 Splines

The following code provides functions to compute manually a cubic spline and returns the penalty function. In R, one would rather use functions that compute efficiently the generalized cross-validation criterion and return the best smoothing or regression spline.

The package splines contains bs for cubic regression splines and ns for natural regression splines. Smoothing splines can be obtained by a call to smooth.spline. The following illustrates a regression spline in which a number of knots (here roughly \(n/10\)) are chosen equispaced on the distribution scale, based on the quantiles of the covariate vector.

The fit from the regression spline differs from that of the smoothing spline. The former uses only 18 basis functions and therefore can be fitted using lm, whereas the smoothing spline uses 94 basis functions (this is lower than \(n\) because there are ties in the x vector).

Below is sample code to obtain the \(\mathbf{B}\) and \(\boldsymbol{\Omega}\) matrices, corresponding to the basis functions and the associated penalty.

For the mcycle data, the following lines of code return those matrices.