在 R 中,如何指定泛型方法采用 ...(点)参数?

In R, how can I specify that a generic method takes a ... (dots) argument?

我在 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.)

因此,如果我们想要一个仅在所有参数均为 "character" 时运行的函数:

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