我正在尝试构建一个通用函数,该函数根据所选算法的类型调度到其他函数。在下面的示例中,算法的类型仅由“ algo1”,“ algo2”等字符选择。x是S4类的对象。参数A和B是所有方法(函数)共有的。我想命名名为Myfun.algo1和Myfun.algo2的函数。这些函数将一些参数设置为一些默认值,因此具有通用性。
#' @export Myfun
Myfun<-function(x, type = c("algo1", "algo2"), A, B, ...){
switch(type,
algo1={res<-do.call(Myfun.algo1, list(x, A, B, ...))},
algo2={res<-do.call(Myfun.algo2, list(x, A, B, ...))},
stop("Unknown Type"))
return(res)
}
#' @rdname MyFun
#' @export
MyFun.algo1<-function(x, A, B, C=2, D=300){
#Do a bit of magic.
}
#' @rdname MyFun
#' @export
MyFun.algo2<-function(x, A, B, E=10, F=1000){
#Do more magic.
}
它可以工作,但是当我检查软件包(使用check()时,我仍然遇到相同的错误:
checking S3 generic/method consistency ... WARNING MyFun: function(x, type, A, B, ...) MyFun.algo1: function(x, A, B, C, D) #Same thing for algo2. See section 'Generic functions and methods' in the 'Writing R Extensions' manual. Found the following apparent S3 methods exported but not registered: MyFun.algo1 MyFun.algo2 See section 'Registering S3 methods' in the 'Writing R Extensions' manual.
我查看了手册,但这确实没有帮助。我尝试通过添加@method和@ S3method来更改roxygen2标签,但没有帮助。我尝试更改...的顺序,并在MyFun的末尾添加了“ type”,但这都没有帮助。我不明白...我在做什么错?为什么我不允许这样做?有没有解决的办法?
在问题代码中,MyFun
不是泛型,并且MyFun.algo1
和MyFun.algo2
不是S3方法,即使名称似乎暗示了这一点。最好将其更改为类似这样的内容,这并不表示不是这样,不会触发任何检查并且更加紧凑。
Myfun <- function(x, type = c("algo1", "algo2"), A, B, ...) {
type <- match.arg(type)
do.call(type, list(x, A, B, ...))
}
algo1 <- function(x, A, B, ...) "algo1"
algo2 <- function(x, A, B, ...) "algo2"
# test run
Myfun(1, "algo1", 2, 3)
## [1] "algo1"
# another test run
Myfun(1, A = 2, B = 3)
## [1] "algo1"