In order to instead fit a natural spline, we use the ns()
function. Here
we fit a natural spline with four degrees of freedom.
fit2 <- lm(wage ~ ns(age, df = 4), data = Wage)
pred2 <- predict(fit2, newdata = list(age = age.grid), se = TRUE)
lines(age.grid, pred2$fit, col = "red", lwd = 2)
As with the bs()
function, we could instead specify the knots directly using
the knots
option.
medv
as dependent variable and lstat
as independent variable.
The spline should have 5 degrees of freedom.
Store the result in the variable fit
.medv
for a series of values of lstat
, ranging from 0 to 50, in steps of 1.
Store the point predictions in the variable preds
. If you use SE = FALSE
in predict()
, the outputs are point predictions; if you use SE = TRUE
, the point predictions are in the attribute fit
.Assume that: