I am using gam
R package. When I use step.Gam()
to perform a stepwise regression I get this error:
Error in as.data.frame.default(data, optional = TRUE) :
cannot coerce class ‘"function"’ to a data.frame
Here is a reproducible example:
library(dplyr)
library(gam)
data(mtcars)
df = mtcars %>% mutate(vs = as.factor(vs),
am = as.factor(am))
f0 = as.formula("mpg ~ cyl + disp + hp + drat + wt + qsec + vs + am + gear + carb")
m.gam.0 = gam(f0, data = df)
f.gam.step = gam.scope(frame = (df %>%
select(mpg, cyl, disp, hp, drat, wt, qsec, vs, am, gear, carb) %>%
as.data.frame()),
response = 1,
arg=c("df=4"))
m.gam.step = step.Gam(object = m.gam.0, scope = f.gam.step, direction="both")
Why do I get this error?
The error is because df
is base R function, hence it is treating the variable df
as a function rather than dataframe. If you change the dataframe name to something else which is not a function name instead of df
it should work.