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

标签 r generics methods

我在 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/

相关文章:

r - 选择除一列之外的所有重复行

java - 在 C++ 中的模板参数上调用静态函数

ajax - 为什么有多种 HTTP 方法可用?

Java : Save Assigned String from method in an array

Rcpp:将编译后的函数保存为 Robj

r - 使一个条形上的边框比其他条形更暗

r - 如何舍入 modelsummary 包中的指标?

java - 泛型类型的集合

generics - 使用 Jackson 序列化 Map<Date, String>

Python:如果变量是整数或 float 则为真