0

I am creating a function to plot various time series plots. I want to plot the ARIMA forecast and also plot the true value being predicted. My code works just fine outside of a function. But, as soon as I put my code in a function, I get the error: Error in FUN(X[[i]], ...) : object 'true.val' not found.

Here's a reproducible example:

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)

If I declare the variable "true.val" outside of the function, the process runs just fine. But, it makes no sense to me why the plot cannot find the variable declared within the function.

  • 1
    I'm getting no error. I tried making a couple different vectors with `rnorm` and had no problem feeding any of them into this function. Sounds silly, but try restarting your R session – camille Jul 03 '18 at 01:55
  • Works for me, other than a different error with the x = as.Date() not being understood, and autoplot not drawing confidence intervals when there's only one prediction point. In your real code, maybe you've missed the `-` from `<-`? eg do you have `true.val < x` instead of `true.val <- x...` – Peter Ellis Jul 03 '18 at 02:00
  • 2
    It's because ggplot don't find 'true.val' as a variable in the prediction data.frame (the object passed to autoplot), so it looks for an object with that name in the global environment. Try to update ggplot2, that issue was corrected in newer versions. Also check this post: https://stackoverflow.com/questions/10659133/local-variables-within-aes – Carlos Eduardo Lagosta Jul 03 '18 at 03:51

0 Answers0