-->

Create a function with different arguments in R

2019-07-24 20:14发布

问题:

I am creating a function that does similar behavior but it would be calling different forecasting algorithms.

modelBuild_auto_arima <- function(data, ...) {
     forecast::auto.arima(data)

   }

modelBuild_ets <- function(data, model, ...) {
   forecast::ets(data, model = model)

 }

...

Is it the best practice to keep it as separate functions and call it separately or create a generic function with "UseMethod". I tried creating with "UseMthod"

modelBuild <- function(x, ...) {
    UseMethod("modelBuild")
   }

modelBuild.auto.arima <- function(x, ...) {
      forecast::auto.arima(x)
  }

modelBuild.ets <- function(x, ...) {
    forecast::ets(x, model = model)
    }

The idea is to call these functions as model building block in a forecasting function

 forecast_all <- function(data, algo_name, h, ...) {
    model <- modelBuild(data, ...)
    forecast::forecast(model, h = h)
   }

Based on the value of 'algo_name' (it can be string or function name ets, auto.arima), 'modelBuild' dispatches the correct method.

回答1:

I would use UseMethod.

You can redefine the class of the data object so that the correct method function is called. For example:

forecast_all <- function(data, algo_name, h, ...) {

  class(data) <- c(class(data), algo_name)

  model <- modelBuild(data, ...)

}