# Calculating spline curve with custom knot positions

I want to fit a spline curve to a simple dataset in R featuring a single custom knot, and extract the resulting models. The data is:

d = data.frame(x = c(3.4,3.9,4.6,5.3,6.2,6.9,7.6,8.5,9.2,9.9,10.8,11.5,13.1,13.8,15.4,16.1),
y = c(5,8,11,14,15,17,18,19,20,21,26,30,40,47,70,90))
plot(d, col = c('black','red')[1+(1:18==8)], pch=16)


I've coloured the approximate knot position red as it looks like the data either side should fit simple exponential curves. I'm unclear what to do next. Unless I'm mistaken splinefun can't accommodate custom knot numbers/positions. Is there a way to achieve this from which the underlying models parameters can be extracted?

I could of course simply split this data into 2 sets and calculate separate models, but I'm keen to use a spline method that can be adapted to modelling more complex curves.

Use the ns function in the splines package, which allows you to specify a knots parameter. Make sure your favorite (I'll take the x position 8.5) is among the knots.
library(splines)
d$splines <- ns(d$x,knots=c(5,8.5,13))
lines(d$x,predict(model))  Then you can look at your model: > model Call: lm(formula = y ~ splines, data = d) Coefficients: (Intercept) splines1 splines2 splines3 splines4 5.618 15.160 15.925 70.300 75.077  • ns calculates piecewise cubic splines, not quadratic ones. In addition, they are natural in the sense that they are linear outside the knots. Without having gone through the details, I think this means that the answer you linked to is not applicable here, i.e., you can't reconstruct d$splines using that answer. The reference in ?ns may be helpful, as may be the splines section in Harrell's Regression Modeling Strategies. Dec 16, 2014 at 16:20
• model is a fitted Ordinary Least Squares model (lm stands for "linear model"), based on d$splines (and an implicit leading intercept column) as the design matrix. If you simply type model, you get the estimated regression coefficients. Dec 16, 2014 at 16:32 • I'm afraid this really exceeds what we can use SE comments for... Do you know matrix algebra? (If not, you'll not get far.) The fit plotted above is really just a matrix (a column of ones, then d$splines), multiplied by a vector for coefficients (in model). Best to learn about OLS (Wikipedia), then understand how ns creates the design matrix of splines, for which the Harrell book (section 2.4.4) is very useful (though very terse). The splines are related to powers of x, but they are not the same, so you don't have relationships between y and x^n. Good luck! Dec 17, 2014 at 8:33