I would like to apply different logistic models to a list of variables in a dataframe. The functions glm()
and lme4::glmer()
as well as mgcv::gam()
work without problems. But the function gam::gam()
I can not use with lapply.
Example:
n <- 1000
y <- rbinom(n,1,0.2)
x1 <- rnorm(n)
x2 <- rnorm(n)
xlist <- list("x1", "x2")
df <- data.frame(y, x1, x2)
library(gam)
#doesn't work
gam_list <- lapply(xlist, function(x){
gam::gam(substitute(y ~ s(i), list(i = as.name(x))), data = df, family = binomial)
})
#Error in terms.default(formula, gam.slist, data = data) :
#no terms component nor attribute
gam <- gam(y ~ s(x1), data = df, family =binomial)
Any ideas how to fix this error?
You can use get
here like below, it should work or eval(parse(text=x))
instead of get
:
gam_list <- lapply(xlist, function(x){
gam::gam(y ~ s(get(x)), data = df, family = binomial)
})
Output:
[[1]]
Call:
gam::gam(formula = y ~ s(get(x)), family = binomial, data = df)
Degrees of Freedom: 999 total; 995 Residual
Residual Deviance: 1010.515
[[2]]
Call:
gam::gam(formula = y ~ s(get(x)), family = binomial, data = df)
Degrees of Freedom: 999 total; 994.9997 Residual
Residual Deviance: 1011.254