The MASS::stepAIC
function takes an lm
result as a parameter and does stepwise regression to find the "best" model. The following code is brain dead simple and works:
library(MASS)
data("mtcars")
lm1 = lm(mpg ~ ., mtcars)
step1 = stepAIC(lm1, direction = "both", trace = FALSE)
I'm trying to put this inside a function. Eventually I want to do more, but I can't even get these two lines of code to work when wrapped in a function:
fit_model = function(formula, data) {
full_model = lm(formula = formula, data = data)
step_model = stepAIC(full_model, direction = "both", trace = FALSE)
return(step_model)
}
step2 = fit_model(mpg ~ ., mtcars)
Error in eval(predvars, data, env) :
invalid 'envir' argument of type 'closure'
I'm running:
R version 3.6.2 (2019-12-12)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Linux Mint 19.1