I wrote a function and each time running it, I get this error:
Error in eval(expr, envir, enclos) : object 'y' not found
However, if I go through my function and run each line separately, it works. What am I doing wrong? Here is my data:
library(vars)
library(forecast)
data <- ts(matrix(rnorm(144, mean=0, sd=1), ncol=6), start=c(2007,1), frequency=12)
colnames(data) <- c("a", "b", "c", "d", "e", "f")
factors <- 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) <- c("f1", "f2")
And my function:
prediction.flex <- function(x, y){
model <- VAR(x, exogen=y, type="const", ic="FPE")
factor.fcst <- sapply(y, function(z) predict(auto.arima(z), n.ahead=6))[1,]
factor.fcst <- cbind(factor.fcst$f1, factor.fcst$f2)
colnames(factor.fcst) <- colnames(y)
forecasting <- predict(model, dumvar=factor.fcst, n.ahead=6, ci=0.95)$fcst$a[,1]
return(forecasting)
}
As I said, when running each line seppeartely using x=data and y=factors, I get the forecast values without an error. However, if I run my function with prediction.flex(data, factors), 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?
vars. - nelakellforecastingisNULL. - user3710546varsandforecastpackages are the only one I load. - nelakell