I am trying to plot a fitted spline with both ns() and smooth.spline() models. When I fit the spline I am unsure how I can set the newdata argument in the prediction function.
For the ns() model, it seems that I have to write the prediction function as predict(fit, newdata= list(x= x.grid))
such that I can plot the fitted curve. If I leave out the newdata
argument it will pop the error of x y differing in length.
For the smooth.spline() model, the prediction looks like this predict(fit, x.grid)$y
. If I add the newdata=
argument it then returns me the x y differing in length
error. Can someone explain why there is such a difference in the use of prediction function?
The code I am working on for natural spline model:
nob = 2
ncubic_ult = glm(mpg~ns(weight, df=2), data = Auto)
autote= Auto[te,]
testweightRange= range(autote$weight)
testweightgrid = seq( from=testweightRange[1], to=testweightRange[2], length.out=100 )
# prediction with list():
fittedmpg= predict(ncubic_ult, newdata = list(weight= testweightgrid))
plot( autote$weight, autote$mpg ,col='grey', main = 'newdata= list')
lines(testweightgrid, fittedmpg, col='red', lw=4)
Smoothing spline:
nob = 3
smooth_ult = smooth.spline(horsepower, mpg, df= nob)
autote= Auto[te,]
test_hpwRange= range(autote$horsepower)
test_hpwgrid = seq( from=test_hpwRange[1], to=test_hpwRange[2], length.out=100 )
fittedmpg= predict(smooth_ult,test_hpwgrid)$y
plot( autote$horsepower, autote$mpg ,col='grey', main = 'newdata= list')
lines(test_hpwgrid, fittedmpg, col='red', lw=4)
```
Auto
withdput(Auto)
? $\endgroup$predict
is a generic and has some methods. Usemethods(predict)
in your console to figure out which methods exist. $\endgroup$