使用不同参数定义S3方法的最佳实践

时间:2017-05-01 10:40:13

标签: r methods documentation arguments

我正在将标准S3方法调度系统添加到我的包(OneR)中,其中我有一个数据框方法和一个公式方法。

我遇到的问题是我对这两种方法都有不同的论点。调用数据框方法时,我不需要data参数,因为数据已存在于x参数中。只有在调用公式方法时才需要data

我是这样做的:

Usage

optbin(x, data, method = c("logreg", "infogain", "naive"), na.omit = TRUE)

## S3 method for class 'formula'
optbin(x, data, method = c("logreg", "infogain", "naive"),
  na.omit = TRUE)

## S3 method for class 'data.frame'
optbin(x, data = x, method = c("logreg", "infogain",
  "naive"), na.omit = TRUE)


Arguments

x  either a formula or a data frame with the last column containing the target variable.
data  data frame which contains the data, only needed when using the formula interface because otherwise 'x' will already contain the data.
method  character string specifying the method for optimal binning, see 'Details'; can be abbreviated.
na.omit  logical value whether instances with missing values should be removed.

我首先想到的是我可以在数据框架方法中省略data参数但是在检查包时我收到警告,因为它出现在UseMethod函数中...当我把它留在那里我得到另一个警告,因为方法之间的不一致。我也试过...但我也收到了警告,除了我必须记录它,这会让用户感到困惑,而不是帮助用户。

但是由于数据框方法中的data = x参数,我也没有找到理想的解决方案。它可能会使人感到困惑,并且是潜在的错误来源。

我的问题
解决这种情况的最佳方法是什么,即当你有两个具有不同参数的方法时?

1 个答案:

答案 0 :(得分:3)

通常的方法是使用除...之外没有额外参数的泛型。每个接口方法都应调用实现实际模型拟合的基础default方法。

optbin <- function(x, ...)
UseMethod("optbin")

optbin.formula <- function(formula, data, method, na.omit, arg1, arg2, ...)
{
  ...
  optbin.default(x, y, arg1, arg2)
}

optbin.data.frame <- function(data, method, na.omit, arg1, arg2, ...)
{
  ...
  optbin.default(x, y, arg1, arg2)
}

optbin.default <- function(x, y, arg1, arg2)
{ ... }

例如,请参阅nnet和MASS包如何处理公式的方法。

相关问题