在R中,我该如何指定一个通用方法接受一个 ...(点)参数?

4

我有一个R语言中的通用方法:

setGeneric(
    "doWork", 
    function(x) { 

        standardGeneric("doWork")
    })

setMethod(
    "doWork", 
    signature = c("character"), 
    definition = function(x) { 

        x
    })

我该如何在定义中添加省略号参数?
1个回答

4
也许我漏掉了什么,但你可以这样做:
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
从R的2.8.0版本开始,S4方法可以被调度(选择和调用)对应于特殊参数“...”。目前,“...”不能与其他形式参数混合使用:通用函数的签名只能是“...”,或者它不包含“...”。(这个限制在未来的版本中可能会被解除。)
因此,如果我们想要一个仅在所有参数都是“字符”时才运行的函数:
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接