Skip to content

Instantly share code, notes, and snippets.

@cbrown5
Created August 4, 2021 10:37
Show Gist options
  • Save cbrown5/d32e74fd237ff27d404137b6a899cff5 to your computer and use it in GitHub Desktop.
Save cbrown5/d32e74fd237ff27d404137b6a899cff5 to your computer and use it in GitHub Desktop.
#Demonstration of splines in R
#Can be used to add nonlinearity to linear models (e.g. GLMs)
library(splines)
x <- rnorm(10000)
n_df <- 5
ns_design_mat <- ns(x, n_df) #n_df degrees of freedom
plot(x, ns_design_mat[,1], ylim = c(-1, 1))
points(x, ns_design_mat[,2], col = "red")
points(x, ns_design_mat[,3], col = "blue")
points(x, ns_design_mat[,4], col = "purple")
points(x, ns_design_mat[,5], col = "orange")
#weights (beta estimates) on each basis
beta <- matrix(c(-3.5, 3.5, -0.5, 0.1, 0.4), nrow = n_df)
ypred <- ns_design_mat %*% beta #similar to predict(m1)
plot(x, ypred)
#to map the splineto new x just use predict(ns_design_mat, newx)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment