My aim is to make a function where you input the variable you want forecasted, and then use cross validation on multiple types of models (ie. Naive, ETS, Mean), then using the 'pull' function I will pull out the model with the lowest RMSE, then I will forecast 1 step ahead with the best model.
However, I am having trouble with the second last line, using the character value 'best.model' as the input for the model when forecasting. (Error is below the code, which you an run yourself).
Here is the code to make more sense:
library(fpp3)
tsibble <- prices
function.fc <- function (variable) {
## cross validation models
cv.fit <- tsibble %>%
select(year, !!sym(variable)) %>%
stretch_tsibble(.init = 180, .step = 1) %>%
filter(.id != max(.id)) %>%
model(
MEAN(!!sym(variable)),
NAIVE(!!sym(variable))
)
## cv forecasts
cv.fc <- cv.fit %>%
forecast(h = 1)
## cv accuracy
cv.accuracy <- cv.fc %>%
accuracy(tsibble)
## pulls out the name of the best model
best.model <- cv.accuracy %>%
select(.model, .type, RMSE) %>%
arrange(RMSE) %>%
filter(row_number(RMSE) == 1) %>%
pull(.model)
## pulls out 1 step forecast
fc <- model(.data = tsibble, noquote(best.model)) %>%
forecast(h = 1)
return(fc)
}
function.fc("copper")
Error: Model definition(s) incorrectly created: noquote(best.model) Check that specified model(s) are model definitions. Run `rlang::last_error()` to see where the error occurred
As you can see I have tried using the 'unquote' function but this still does not work. Does anyone have any suggestions on what to use? I have struggled to find other posts with my problem.