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.