Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fit all variables using splines with gam in R without typing each one?

Tags:

r

mgcv

gam

Lets say I have a data set with y and x1, x2, xp variables. I want to fit all of my predictors with splines.

For example :

gam_object = gam(y ~ s(x1) + s(x2) + s(xp), data)

How can I do this without typing every single variable? If I would like to fit the module without the first two without using splines. How can I do that?

gam_object2 =  gam(y ~ x1 + x2 + s(x1) + s(x2), data)
like image 488
Jixxi Avatar asked Sep 14 '25 07:09

Jixxi


1 Answers

Maybe this could help you:

p<-10
as.formula(paste0("y~",paste0("s(x",1:p,")",collapse="+")))

If you don't want to use first two or more generally don't use splines on some specific variables use:

data<- #yours data
use<-c(3:6,9:10)
dontuse<-c(1:2,7:8)
form<-as.formula(
 paste0("y~",paste0("s(x",use,")",collapse="+"),"+",paste0("x",dontuse,collapse="+"),collapse=""))

And then run model:

gam(data=data,formula=form,family=gaussian)
like image 152
Maju116 Avatar answered Sep 17 '25 00:09

Maju116