1

Say I have this as my dataframe:

    library(fpp3)
    df <- prices

And I want to create a function where I pass in the variable name and the number of steps forward I want to forecast. This is the function I have tried, which does not work. (I have used the 'select' function as I am doing cross-validation on my time series, but I do not need to include that code in this example)

fc.function <- function(variable, steps) {

fit <- df %>%
  select(year, variable) %>%
  model(
    MEAN(variable)
  ) 

fit %>%
  forecast(h = steps)

}

When I use the variable 'copper' for example and I forecast 1 step ahead I get an error.

fc.function("copper", 1)

Error in FUN(X[[i]], ...) : object 'variable' not found
Called from: FUN(X[[i]], ...)

I have looked at multiple different answers on here but unless I missed or misinterpreted a solution, which I may have, then I cannot find my answer.

user438383
  • 5,716
  • 8
  • 28
  • 43
  • This question gives the same answer you are looking for https://stackoverflow.com/questions/67382081/passing-argument-from-custom-function-to-group-by-doesnt-work/67382231#67382231 – user438383 May 04 '21 at 13:07

1 Answers1

1

You are providing your function with the character value "copper" (and not a symbol). You can convert to a symbol with sym and then unquote using !! within the dplyr statements.

fc.function <- function(variable, steps) {
  df %>%
    select(year, !!sym(variable)) %>%
    model(MEAN(!!sym(variable))) %>%
    forecast(h = steps)
}
Ben
  • 28,684
  • 5
  • 23
  • 45