简体   繁体   中英

R for loop within model

I would like to run a for loop within a model in R, so that I can run through a list of possible degrees of freedom without typing each individual. Finally storing the mean squared error of all possible 50 degrees of freedom in the mse vector. I can't quite get the syntax correct...

Any help would be greatly appreciated.

I would like to set

grid = seq(0,50)
gam.mod = gam(balance~income+ns(age,df=**grid**)+student,data=credit[train,])
pred.mod = predict(gam.mod,newdata=credit[test,])
*mse* = mean((pred.mod-balance[test])^2)

You can use a loop, for example

grid <- seq(0, 50)
sapply(grid, function(i){
  gam.mod <- gam(balance~income + ns(age, df = i) + student, data = credit[train, ])
  pred.mod <- predict(gam.mod, newdata = credit[test,])
  mse <- mean((pred.mod - balance[test])^2) 
  mse
})

You could try this loop. Advisable to paste and create a separate model instead of putting the looping variable directly into the gam function.

mse <- rep(NA, 51)
names(mse) <- 0:50 
for(i in 0:50){
    gam.form <- as.formula(paste0("balance~income+ns(age,df=", i, ")+student"))
    gam.mod <- gam(gam.form,data=credit[train,])
    pred.mod <- predict(gam.mod,newdata=credit[test,])
    mse[as.character(i)] <- mean((pred.mod-balance[test])^2)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM