我在 R 中有一个通用方法:
setGeneric(
"doWork",
function(x) {
standardGeneric("doWork")
})
setMethod(
"doWork",
signature = c("character"),
definition = function(x) {
x
})
如何在定义中添加 ...(点)参数?
最佳答案
也许我错过了一些东西,但你可以这样做:
setGeneric("doWork", function(x, ...) standardGeneric("doWork"))
setMethod("doWork", signature = c("character"),
function(x, ...) do.call(paste, list(x, ..., collapse=" "))
)
然后:
> doWork("hello", "world", letters[1:5])
[1] "hello world a hello world b hello world c hello world d hello world e"
> doWork(1:3, "world", letters[1:5])
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘doWork’ for signature ‘"integer"’
您甚至可以在
...
上发送如果你想在某些情况下。来自 ?dotsMethods
:Beginning with version 2.8.0 of R, S4 methods can be dispatched (selected and called) corresponding to the special argument “...”. Currently, “...” cannot be mixed with other formal arguments: either the signature of the generic function is “...” only, or it does not contain “...”. (This restriction may be lifted in a future version.)
因此,如果我们想要一个仅在所有参数都是“字符”时运行的函数:
setGeneric("doWork2", function(...) standardGeneric("doWork2"))
setMethod("doWork2", signature = c("character"),
definition = function(...) do.call(paste, list(..., collapse=" "))
)
doWork2("a", "b", "c") # [1] "a b c"
doWork2("a", 1, 2) # Error
关于r - 在 R 中,如何指定泛型方法采用 ...(点)参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30396232/