title: Object not found error when passing model formula to another function
body: <p>I have a weird problem with R that I can't seem to work out.</p>
  
  <p>I've tried to write a function that performs K-fold cross validation for a model chosen by the stepwise procedure in R. (I'm aware of the issues with stepwise procedures, it's purely for comparison purposes) :)</p>
  
  <p>Now the issue is, that if I define the function parameters (linmod,k,direction) and run the contents of the function, it works flawlessly. BUT, if I run it as a function, I get an error saying the datas.train object can't be found. </p>
  
  <p>I've tried stepping through the function with debug() and the object clearly exists, but R says it doesn't when I actually run the function. If I just fit a model using lm() it works fine, so I believe it's a problem with the step function in the loop, while inside a function. (try commenting out the step command, and set the predictions to those from the ordinary linear model.)</p>
  
  <pre><code>#CREATE A LINEAR MODEL TO TEST FUNCTION
  lm.cars &lt;- lm(mpg~.,data=mtcars,x=TRUE,y=TRUE)
  
  
  #THE FUNCTION
  cv.step &lt;- function(linmod,k=10,direction="both"){
    response &lt;- linmod$y
    dmatrix &lt;- linmod$x
    n &lt;- length(response)
    datas &lt;- linmod$model
    form &lt;- formula(linmod$call)
  
    # generate indices for cross validation
    rar &lt;- n/k
    xval.idx &lt;- list()
    s &lt;- sample(1:n, n) # permutation of 1:n
    for (i in 1:k) {
      xval.idx[[i]] &lt;- s[(ceiling(rar*(i-1))+1):(ceiling(rar*i))]
    }
  
    #error calculation
    errors &lt;- R2 &lt;- 0
  
    for (j in 1:k){
       datas.test &lt;- datas[xval.idx[[j]],]
         datas.train &lt;- datas[-xval.idx[[j]],]
         test.idx &lt;- xval.idx[[j]]
  
         #THE MODELS+
         lm.1 &lt;- lm(form,data= datas.train)
         lm.step &lt;- step(lm.1,direction=direction,trace=0)
  
        step.pred &lt;- predict(lm.step,newdata= datas.test)
          step.error &lt;- sum((step.pred-response[test.idx])^2)
          errors[j] &lt;- step.error/length(response[test.idx])
  
          SS.tot &lt;- sum((response[test.idx] - mean(response[test.idx]))^2)
          R2[j] &lt;- 1 - step.error/SS.tot
    }
  
    CVerror &lt;- sum(errors)/k
    CV.R2 &lt;-  sum(R2)/k
  
    res &lt;- list()
    res$CV.error &lt;- CVerror
    res$CV.R2 &lt;- CV.R2
  
  return(res)
  }
  
  
  #TESTING OUT THE FUNCTION
  cv.step(lm.cars)
  </code></pre>
  
  <p>Any thoughts?</p>