j.barrio
j.barrio

Reputation: 1036

compare splines and polynomials

I'm trying to write a function to compare the basic model between splines and polynomial regression. But when I use model$formula option, that I have in my model, and use it into a gam function with the next variable, I receive an error:

Error in mod$formula + df_work_final$Apps :
non-numeric argument to binary operator

How I can use my model formula into the function?

Thank You

Complete example:

library(gam)
library(ISLR)
data(College)

mod = gam(College$Grad.Rate~College$Private)

# This, I want to use into a function
Poly = function(valores){
    poly.1= gam(mod$formula + valores,data=College)
    poly.2= gam(mod$formula + poly(valores,2) ,data=College)
    poly.3= gam(mod$formula + poly(valores,3) ,data=College)
    poly.4= gam(mod$formula + poly(valores,4) ,data=College)
    poly.5= gam(mod$formula + poly(valores,5) ,data=College)
}

Poly(df_work_final$Apps)

Upvotes: 2

Views: 402

Answers (1)

Zheyuan Li
Zheyuan Li

Reputation: 73315

Moving my previous comments into an answer:

  • In any case, using $ in a model formula should be prohibited; use data argument of model fitting functions instead;

  • I don't see any smooth function in your initial gam, like lo or s. You are really just fitting a linear model Grad.Rate ~ Private. So, why not use

    mod <- lm(Grad.Rate ~ Private, data = College)
    
  • + is invalid for concatenation of formula. You want to use update.formula (read ?update.formula for more), for example,

    update.formula(formula(mod), . ~ . + poly(Apps, 2))
    

Upvotes: 1

Related Questions