rdataframefunctiontime-seriestsibble

Using Time Series Models Inside Custom R Functions


I am attempting to create an R function that takes in a tsibble and column name, fits a few basic models, and will eventually output a plot (though the plotting portion is not the subject of this question).

At this point, I cannot get the following code to work:

base_line_models <- function(dataframe, column) {
  col_name <- enquo(column)
  #col_name  <- as.name(column)

  
  df_fit <- dataframe %>%
    model(
      Mean = MEAN(!!col_name),
      `Naïve` = NAIVE(!!col_name),
      Drift = NAIVE((!!col_name) ~ drift())
    )
  
  return(df_fit)
}

base_line_models(souvenirs, 'Sales')
# using the souvenirs tsibble from the fpp3 package

It returns: Error: 'call' must be a quoted call , which I have searched to no avail and does not make sense to me because, from everything I can see, I am calling the function.

I had a feeling this has to do with how R handles dataframes inside of functions, so I have also tried using {{column}} and {{col_name}} in place of the enquo() / !!column calls, but this has not worked.

Fair warning, I am a Python guy, so my approaches may not be standard R fare. Please feel free to point out if my approach is incorrect.


Solution

  • Your code is basically correct; uncomment the second line col_name <- as.name(column) and remove the one above it. I ran it that way and didn't have any issues.

    Typically when working with the fpp3 package, you may want to consider using tsibbles instead of standard dataframe objects. While your code works, if you're looking to add additional functionality that ends up running into issues using dataframe objects, consider turning them into tsibbles. All it requires is a simple tweak

    library(fpp3)
    library(tidyverse)
    
    data("souvenirs")
    
    base_line_models <- function(dataframe, column) {
      myTsibble <- as_tsibble(dataframe)
      col_name <- as.name(column)
      
      tsibble_fit <- myTsibble %>%
        model(
          Mean = MEAN(!!col_name),
          `Naïve` = NAIVE(!!col_name),
          Drift = NAIVE((!!col_name) ~ drift())
        )
      
      return(tsibble_fit)
    }
    
    
    
    base_line_models(souvenirs, 'Sales')