Create a function with different arguments in R

折月煮酒 提交于 2020-02-04 08:42:12

问题


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, ...)

}


来源:https://stackoverflow.com/questions/55091625/create-a-function-with-different-arguments-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!