I realized a strange behavior today with in my R code.
I tried a package {boot.StepAIC} which includes a bootstrap function for the results of the stepwise regression with the AIC. However I do not think the statistical background is here the problem (I hope so).
I can use the function at the top level of R. This is my example code.
require(MASS)
require(boot.StepAIC)
n<-100
x<-rnorm(n); y<-rnorm(n,sd=2); z<-rnorm(n,sd=3); res<-x+y+z+rnorm(n,sd=0.1)
dat.test<-as.data.frame(cbind(x,y,z,res))
form.1<-as.formula(res~x+y+z)
boot.stepAIC(lm(form.1, dat.test),dat.test) # should be OK - works at me
However, I wanted to wrap that in an own function. I pass the data and the formula to that function. But I get an error within boot.stepAIC() saying:
the model fit failed in 100 bootstrap samples Error in strsplit(nam.vars, ":") : non-character argument
# custom function
fun.boot.lm.stepAIC<-function(dat,form) {
if(!inherits(form, "formula")) stop("No formula given")
fit.lm<-lm(formula=form,data=dat)
return(boot.stepAIC(object=fit.lm,data=dat))
}
fun.boot.lm.stepAIC(dat=dat.test,form=form.1)
# results in an error
So where is the mistake? I suppose it must have something to do with the local and global environment, doesn't it?
boot.stepAIC
before but suspect it may also have to do with how the formula being passed into the function (which is related to the environment issues too). See https://mcmap.net/q/662973/-understanding-lm-and-environment, https://mcmap.net/q/920420/-anova-test-fails-on-lme-fits-created-with-pasted-formula for some ideas. In particular, callinglm
orboot.stepAIC
viado.call
may help as then the arguments are evaluated before being passed in. You may also investigate theas.name
suggestion in the comments. These issues are tricky -- good luck! – Venettavenezia