在S4通用方法中将...与正式参数混合使用

3

来自?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.)

这是来自EBImage包的一些代码:

## image IO, display
setGeneric ("image", function (x, ...) standardGeneric("image") )

## statistics
setGeneric ("hist", function (x, ...) standardGeneric("hist") )

看起来这似乎违反了“…”不能与其他形式参数混合使用的规则。这是否意味着限制已经被取消但未记录在案?

2个回答

5
您引用的部分中的关键词是“dispatched”。在这里,“dispatched”意味着将任务发送到队列中,以便稍后执行。
setGeneric("foo", function(x, ...) standardGeneric("foo"))

您可以根据 'x' 的类编写方法。

.A = setClass("A", "integer")
.B = setClass("B", "integer")
setMethod("foo", "A", function(x, ...) "foo,A-method")

'...'仍可用于提供特定于方法的参数,但没有可用于“...”的分派。

setMethod("foo", "B", function(x, barg, ...) sprintf("barg=%d", barg))

使用

> foo(.B(), barg=123)
[1] "barg=123"

这是EBImage如何使用“...”,这是一个非常常见的用例。
在这里:
setGeneric("bar", function(...) standardGeneric("bar"))

如果所有的类别相同,您可以编写基于“...”的调度方法

setMethod("bar", "A", function(...) "bar,A-method")

使用

> bar(.A(), .A())
[1] "bar,A-method"
> bar(.A(), .B())
Error in standardGeneric("bar") : 
  no method or default matching the "..." arguments in bar(.A(), .B())
> setMethod("bar", c("A", "B"), function(...) "bar,A,B-method")
Error in matchSignature(signature, fdef) : 
  more elements in the method signature (2) than in the generic signature (1) for function 'bar'

上述代码使用隐式规则确定签名,getGeneric()会显示分派的参数,其中输出指示“可以为参数定义方法:”,例如:
> getGeneric("foo")
standardGeneric for "foo" defined from package ".GlobalEnv"

function (x, ...) 
standardGeneric("foo")
<environment: 0x2ba550a0>
Methods may be defined for arguments: x
Use  showMethods("foo")  for currently available ones.
> getGeneric("bar")
standardGeneric for "bar" defined from package ".GlobalEnv"

function (...) 
standardGeneric("bar")
<environment: 0x2c127e58>
Methods may be defined for arguments: ...
Use  showMethods("bar")  for currently available ones.

R似乎可以让您定义在x混合的泛型分派...

> setGeneric("baz", function(x, ...) standardGeneric("baz"), 
             signature=c("x", "..."))
[1] "baz"

但实际上情况并非如此。
> getGeneric("baz")
standardGeneric for "baz" defined from package ".GlobalEnv"

function (x, ...) 
standardGeneric("baz")
<environment: 0x2c704cc0>
Methods may be defined for arguments: x
Use  showMethods("baz")  for currently available ones.

0

可以在 s4 通用函数中与其他形式参数一起使用 ...。您还应该记得将其作为参数之一包含在 setMethod 函数中。


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