0

我正在创建一个函数来绘制各种时间序列图。我想绘制 ARIMA 预测并绘制预测的真实值。我的代码在函数之外工作得很好。但是,一旦我将代码放入函数中,我就会收到错误: Error in FUN(X[[i]], ...) : object 'true.val' not found.

这是一个可重现的示例:

library(forecast)
library(ggplot2)
#install_github('sinhrks/ggfortify')
library(ggfortify)

data <- c(1260.00480466826,1093.9149606944,1161.52359871238,1369.25480458625,1261.16383359509,1215.82252739366,1283.13994373127,1384.35154519889,1420.76668434656,1313.69077983755,1380.81589795889,1553.76667281431,1509.0003428258,1375.8601831797,1511.89811213627,1588.76024038283,1574.42367287576,1422.07495995585,1460.50565733634,1616.71792111546,1722.0566597863,1421.77814339745,1435.82356628016,2003.57843137255)
my.fun <- function(x){
  true.val <- x[length(x)]
  data.ts <- ts(x[-length(x)], start = c(2012, 1), end = c(2017, 3), frequency = 4)
  arima.fit <- auto.arima(data.ts)
  prediction <- forecast(arima.fit, h = 1, level = 99)
  p <- autoplot(prediction) + geom_point(aes(x = as.Date("10/1/2017", format = "%m/%d/%Y"), y = true.val))
  return(p)
}

my.fun(data)

如果我在函数之外声明变量“true.val”,则该过程运行得很好。但是,为什么绘图找不到函数中声明的变量对我来说毫无意义。

4

0 回答 0