rtidyverserlangfable

string as function argument in R inside map


Question: i have the following R code (below): It didn't work with "x" = "ARIMA" and "ETS" from "my.list". That's the problem: "fabletools::model(arima_auto = fable::ARIMA(Trips))" = it works, but this: "fabletools::model(arima_auto = fable::x(Trips))" didn't work. Does anyone know the solution to my problem. Is it even possible in R?

library(tidyverse)
library(fable)
library(fabletools)
library(tsibble)

tourism <- tsibble::tourism 

my.list <- list("ARIMA","ETS")

my.list[[1]] ## "ARIMA"
my.list[[2]] ## "ETS"

f_test <- function(.df1,.n){

  x <- .df1[[.n]][[1]] ### 1) "ARIMA", "ETS"
  print(x)
  
  fit <- tourism %>%
    dplyr::filter(Region == "Adelaide") %>%
    #fabletools::model(arima_auto = fable::ARIMA(Trips)) ### it works
    fabletools::model(arima_auto = fable::x(Trips)) ### didn't work
  
  assign("fit", fit, envir= globalenv())
} 

purrr::map(.x = seq(my.list), .f = ~(f_test(my.list, Counter <- .x)))

Solution

  • When you're calling x(Trips), your x is the character vector "ARIMA". R has no idea what [character vector](Trips) means. It would be like trying to call "Alice"(y) and expecting R to treat "Alice" as a function, even though it clearly is not one.

    What you want is a way for R to swap the string "ARIMA" for its corresponding function. This is what match.fun is for. Try this instead:

    working<-match.fun(x)
    fabletools::model(arima_auto = working(Trips))
    

    Note that we didn't need to use any namespaces for this, unlike your original approach. Good practice would be to find a way to do so, e.g. working<-get(x,envir = environment(fable)), but we didn't need it here.