title: Error running a function: Error in eval(expr, envir, enclos) : object not found
body: <p>I wrote a function and each time running it, I get this error: </p>
  
  <blockquote>
    <p>Error in eval(expr, envir, enclos) : object 'y' not found </p>
  </blockquote>
  
  <p>However, if I go through my function and run each line separately, it works. What am I doing wrong? Here is my data:</p>
  
  <pre><code>library(vars)
  library(forecast)
  data &lt;- ts(matrix(rnorm(144, mean=0, sd=1), ncol=6), start=c(2007,1), frequency=12) 
  colnames(data) &lt;- c("a", "b", "c", "d", "e", "f")
  factors &lt;- ts(t(t(eigen(cor(data))$vectors[,1:2] %*% 
                         sqrt(diag(eigen(cor(data))$values[1:2]))) %*% 
                       t(scale(data))), start=c(2007,1), frequency=12)
  colnames(factors) &lt;- c("f1", "f2")
  </code></pre>
  
  <p>And my function:</p>
  
  <pre><code>prediction.flex &lt;- function(x, y){
    model &lt;- VAR(x, exogen=y, type="const", ic="FPE")
    factor.fcst &lt;- sapply(y, function(z) predict(auto.arima(z), n.ahead=6))[1,]
    factor.fcst &lt;- cbind(factor.fcst$f1, factor.fcst$f2)
    colnames(factor.fcst) &lt;- colnames(y)
    forecasting &lt;- predict(model, dumvar=factor.fcst, n.ahead=6, ci=0.95)$fcst$a[,1]
    return(forecasting)
  }
  </code></pre>
  
  <p>As I said, when running each line seppeartely using <code>x=data</code> and <code>y=factors</code>, I get the forecast values without an error. However, if I run my function with <code>prediction.flex(data, factors)</code>, it tells me that object y wasn't found. Rerunning with debug shows that the line with the forecasting is the problem, even though I just use objects in it, which I generated during the function. I don't understand the error. Do you know where my mistake is?</p>