运行函数时出错:eval(expr,envir,enclos)中出错:找不到对象

时间:2015-09-09 08:08:26

标签: r function

我写了一个函数,每次运行它都会出现这个错误:

  

eval(expr,envir,enclos)中的错误:object' y'找不到

但是,如果我通过我的功能并分别运行每一行,它就可以工作。我究竟做错了什么?这是我的数据:

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")

我的功能:

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)
}

正如我所说,当使用x=datay=factors安全地运行每一行时,我会得到预测值而没有错误。但是,如果我使用prediction.flex(data, factors)运行我的函数,它会告诉我找不到对象y。使用调试进行重新运行表明,带有预测的行是问题所在,即使我只是在其中使用了我在函数期间生成的对象。我不明白这个错误。你知道我的错误在哪里吗?

1 个答案:

答案 0 :(得分:1)

以下是一种可行的解决方法,将y分配给全局环境:

library(vars)
library(forecast)

set.seed(42)
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")
prediction.flex <- function(x, y){
  model <- VAR(x, exogen=y, type="const", ic="FPE")
  # Assigning "y" to the global environment
  assign("y", "y", envir = .GlobalEnv)
  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)
}
out1 <- prediction.flex(data, factors)

x <- data
y <- factors
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)
out2 <- predict(model, dumvar=factor.fcst, n.ahead=6, ci=0.95)$fcst$a[,1]

all.equal(out1, out2)
# [1] TRUE