Reputation: 20463
Take for instance the following one-knot, degree one, spline:
library(splines)
library(ISLR)
age.grid = seq(range(Wage$age)[1], range(Wage$age)[2])
fit.spline = lm(wage~bs(age, knots=c(30), degree=1), data=Wage)
pred.spline = predict(fit.spline, newdata=list(age=age.grid), se=T)
plot(Wage$age, Wage$wage, col="gray")
lines(age.grid, pred.spline$fit, col="red")
# NOTE: This is **NOT** the same as fitting two piece-wise linear models becase
# the spline will add the contraint that the function is continuous at age=30
# fit.1 = lm(wage~age, data=subset(Wage,age<30))
# fit.2 = lm(wage~age, data=subset(Wage,age>=30))
Is there a way to extract the linear model (and its coefficients) for before and after the knot? That is, how can I extract the two linear models before and after the cut point of age=30
?
Using summary(fit.spline)
yields coefficients, but (to my understanding) they are not meaningful for interpretation.
Upvotes: 5
Views: 2767
Reputation: 1
Extracting the knots is primarily done when you pre-specify degrees of freedom in your bspline regression. Example:
fit.spline = lm(wage~bs(age, df=5), data=Wage)
attr(bs(age,df=5),"knots")
33.33333% 66.66667%
37 48
An example can be found in the ISLR book (which you appear to be using) on page 293.
Upvotes: 0
Reputation: 5314
You can extract the coefficients manually from fit.spline
like this
summary(fit.spline)
Call:
lm(formula = wage ~ bs(age, knots = 30, degree = 1), data = Wage)
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 54.19 4.05 13.4 <2e-16 ***
bs(age, knots = 30, degree = 1)1 58.43 4.61 12.7 <2e-16 ***
bs(age, knots = 30, degree = 1)2 68.73 4.54 15.1 <2e-16 ***
---
range(Wage$age)
## [1] 18 80
## coefficients of the first model
a1 <- seq(18, 30, length.out = 10)
b1 <- seq(54.19, 58.43+54.19, length.out = 10)
## coefficients of the second model
a2 <- seq(30, 80, length.out = 10)
b2 <- seq(54.19 + 58.43, 54.19 + 68.73, length.out = 10)
plot(Wage$age, Wage$wage, col="gray", xlim = c(0, 90))
lines(x = a1, y = b1, col = "blue" )
lines(x = a2, y = b2, col = "red")
If you want the coefficients of the slope like in a linear model then you can simply use
b1 <- (58.43)/(30 - 18)
b2 <- (68.73 - 58.43)/(80 - 30)
Note that in fit.spline
the intercept means the value of wage
when age = 18
whereas in a linear model the intercept means the value wage
when age = 0
.
Upvotes: 1