It is a follow up to the posted question Create a function with different arguments in R
I created a generic function but got stuck with passing different set of parameters to these functions
modelBuild <- function(x, ...) {
UseMethod("modelBuild")
}
modelBuild.auto.arima <- function(x, ...) {
forecast::auto.arima(x)
}
Now, I want to add a parameter model
into modeBuild.ets
modelBuild.ets <- function(x, model, ...) {
forecast::ets(x, model = model)
}
and a different parameter in nnetar
modelBuild.nnetar <- function(x, repeats, ...) {
forecast::nnetar(x, repeats = repeats)
}
The modelBuild
function is called by another function
forecast_all <- function(data, algo_name, model = "ZZZ", repeats = 20 , ...) {
class(data) <- c(class(data), algo_name)
modelBuild(data, model, repeats, ...)
}
Now, we test on a reproducible example
set.seed(1)
a <- runif(100) * 2.5
forecast_all(a, "auto.arima")
Series: x
ARIMA(0,0,0) with non-zero mean
Coefficients:
mean
1.2946
s.e. 0.0666
sigma^2 estimated as 0.4475: log likelihood=-101.19
AIC=206.38 AICc=206.5 BIC=211.59
forecast_all(a, "ets", model = "ZZZ")
ETS(M,N,N)
Call:
forecast::ets(y = x, model = model)
Smoothing parameters:
alpha = 1e-04
Initial states:
l = 1.2947
sigma: 0.5194
AIC AICc BIC
385.1151 385.3651 392.9306
the nnetar
results in error
forecast_all(a, "nnetar", repeats = 22)
Error in 1:repeats : NA/NaN argument
In addition: Warning message:
In avnnet(lags.X[j, , drop = FALSE], y[j], size = size, repeats = repeats, :
NAs introduced by coercion
Inorder to correct it, I included all the parameters as input in each of the modelBuild
modelBuild.auto.arima <- function(x, model, repeats, ...) {
forecast::auto.arima(x)
}
modelBuild.ets <- function(x, model, repeats, ...) {
forecast::ets(x, model = model)
}
modelBuild.nnetar <- function(x, model, repeats, ...) {
forecast::nnetar(x, repeats = repeats)
}
Now, all the functions work as expected
forecast_all(a, "auto.arima")
Series: x
ARIMA(0,0,0) with non-zero mean
Coefficients:
mean
1.2946
s.e. 0.0666
sigma^2 estimated as 0.4475: log likelihood=-101.19
AIC=206.38 AICc=206.5 BIC=211.59
forecast_all(a, "ets", model = "ZZZ")
ETS(M,N,N)
Call:
forecast::ets(y = x, model = model)
Smoothing parameters:
alpha = 1e-04
Initial states:
l = 1.2947
sigma: 0.5194
AIC AICc BIC
385.1151 385.3651 392.9306
forecast_all(a, "nnetar", repeats = 22)
Series: x
Model: NNAR(1,1)
Call: forecast::nnetar(y = x, repeats = repeats)
Average of 22 networks, each of which is
a 1-1-1 network with 4 weights
options were - linear output units
sigma^2 estimated as 0.4297
Is this the best practice to create generic functions in R
or is there a way to define a method with limited parameters for each methodBuild
can still call it without having to define parameters that are not required for a particular function. I am looking for a similar behavior of overloading functions as in java
Can this be solved in S4
or R6
method system?