这是对已发布问题的后续行动Create a function with different arguments in R
我创建了一个通用函数,但遇到了将不同的参数集传递给这些函数的问题
modelBuild <- function(x, ...) {
UseMethod("modelBuild")
}
modelBuild.auto.arima <- function(x, ...) {
forecast::auto.arima(x)
}
现在,我想添加一个model
参数modeBuild.ets
modelBuild.ets <- function(x, model, ...) {
forecast::ets(x, model = model)
}
和一个不同的参数nnetar
modelBuild.nnetar <- function(x, repeats, ...) {
forecast::nnetar(x, repeats = repeats)
}
该modelBuild
函数被另一个函数调用
forecast_all <- function(data, algo_name, model = "ZZZ", repeats = 20 , ...) {
class(data) <- c(class(data), algo_name)
modelBuild(data, model, repeats, ...)
}
现在,我们测试一个可重现的例子
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
结果nnetar
错误
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
为了更正它,我将所有参数作为输入包含在每个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)
}
现在,所有功能都按预期工作
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
这是在其中创建泛型函数的最佳实践,R
还是有一种方法可以定义具有有限参数的方法,每个methodBuild
方法仍然可以调用它,而无需定义特定函数不需要的参数。我正在寻找类似的重载函数行为,如java
这可以在S4
或R6
方法系统中解决吗?