Skip to content

Instantly share code, notes, and snippets.

@tjmahr
Created May 7, 2024 20:58
Show Gist options
  • Save tjmahr/58da62a283ba54289d60236328e33b59 to your computer and use it in GitHub Desktop.
Save tjmahr/58da62a283ba54289d60236328e33b59 to your computer and use it in GitHub Desktop.
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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment