gpt4 book ai didi

r - S3 通用/方法一致性 - 如何根据所选类型进行调度?

转载 作者:行者123 更新时间:2023-12-04 10:51:55 24 4
gpt4 key购买 nike

我正在尝试构建一个通用函数,该函数根据选择的算法类型调度到其他函数。在下面的示例中,算法的类型只是由“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 的末尾,但也没有帮助。我不明白……我做错了什么?为什么不允许我这样做?有没有解决的办法?

最佳答案

在问题中的代码 MyFun不是通用的和 MyFun.algo1MyFun.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"

关于r - S3 通用/方法一致性 - 如何根据所选类型进行调度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59439184/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com