Search code examples
rgam

fit a smoothing spline using gam function


I want to fit a smoothing spline using gam function. An attempt to plot the fitted values is resulting in an error -object$nsdf? I am wondering if that is a needed input and if so what is df referring to? How to fix this code.

gam.fit=gam(y~s(disp,6)+s(hp,5)+s(wt,5), data=train.dat)
mean((test.dat$y - gam.pred)^2)  # 0.0002282536
plot(gam.fit, se=TRUE, col="blue",main="10.3f.gam")
# Error in 1:object$nsdf : argument of length 0

Thank you. Sincerely, Mary A. Marion


Solution

  • Your gam() call syntax:

    gam.fit=gam(y~s(disp,6)+s(hp,5)+s(wt,5), data=train.dat)
    

    suggests that you are using package gam instead of mgcv. However, the error you get, which complains about object$nsdf, is produced from mgcv package. Do not load both packages into your R session at the same time!!.

    library(gam)
    set.seed(0)
    dat <- data.frame(x1 = rnorm(100), x2 = rnorm(100), x3 = rnorm(100),
                      y = rnorm(100))
    fit <- gam(y ~ s(x1,6) + s(x2,5) + s(x3,5), data = dat)
    par(mfrow = c(1,3)); plot.gam(fit)
    

    enter image description here