Hello!
I would like to use step() in a function because I have a list of responses
(independent!) with equal influence and want to apply stepwise regression on
each of them. So the function I just tested is the following:
fitlms <- function(y,infl,formel=NULL){
if(is.null(formel)){
var.names <- names(infl)
dcv <- length(var.names)
formel <- paste("y~",paste(rep("I(",dcv), var.names,
rep("^2)",dcv),sep="",collapse="+"),"+",paste(var.names,collapse="*"),sep="")
formel <- as.formula(formel)
}
erg <- lm(formel,infl)
erg <- step(erg)
return(erg)}
Using this I get the following:
test <- fitlms(grob.erg[,1],grob.erg[,3:5])
Start: AIC= -30.84
y ~ I(f^2) + I(vS^2) + I(o^2) + f + vS + o + f:vS + f:o + vS:o +
f:vS:o
Df Sum of Sq RSS AIC
- f:vS:o 1 0.060 2.052 -32.188
<none> 1.992 -30.842
- I(o^2) 1 0.762 2.754 -25.717
- I(f^2) 1 2.581 4.573 -14.558
- I(vS^2) 1 5.341 7.333 -4.170
Error in model.frame.default(formula = y ~ I(f^2) + I(vS^2) + I(o^2) + :
Object "infl" not found
So the first step carried out correctly and then it seems to look into the
wrong environment (presumably the top-level). I checked with the code of step,
but could not spot the cause of this behaviour. At some place it looks
at the parent.frame, which should be the environment created by function fitlms
if I do unserstand things correctly. I checked also whether I can give step an
environment in which to operate, but could not find any such option.
I presume I could just use a for-loop, which might not be much slower than
lapply in this case. I simply would like to understand things better to avoid
similar errors.
Data is given below.
Thanks for your attention and any help appreciated,
Winfried