library(splines)
model <- lm(mpg ~ ns(wt, df = 3), mtcars)
# make and plot a basis
basis <- ns(sort(mtcars$wt), df = 3)
matplot(basis, type = "l")
# apply basis to new xs with predict()
x_range <- seq(min(mtcars$wt), max(mtcars$wt), length.out = 100)
new_x <- predict(basis, x_range)
# smoother!
matplot(new_x, type = "l")
# smooth predictions - by hand and automatically
plot(x_range, cbind(1, new_x) %*% coef(model))
plot(x_range, predict(model, data.frame(wt = x_range)))
Created on 2024-05-07 with reprex v2.1.0