假设与特定 S4 通用函数/方法关联的所有S4 方法共享一个应该具有特定默认值的形式参数。直观地说,我会在 S4泛型的定义中陈述这样一个论点(而不是在每个方法定义中陈述它,这对我来说似乎有些多余)。
但是,我注意到这样我遇到了麻烦,因为似乎形式参数的默认值没有分派给方法,因此引发了错误。
这不是有点反对结合泛型和方法的想法吗?当默认值始终相同时,为什么我必须再次在每个方法中分别声明形式参数?我可以以某种方式显式分派形式参数的默认值吗?
您将在下面找到该行为的简短说明
通用函数
setGeneric(
name="testFoo",
signature=c("x", "y"),
def=function(
x,
y,
do.both=FALSE,
...
) {
standardGeneric("testFoo")
}
)
方法
setMethod(
f="testFoo",
signature=signature(x="numeric", y="numeric"),
definition=function(
x,
y
) {
if (do.both) {
out <- list(x=x, y=y)
} else {
out <- x
}
return(out)
}
)
错误
> testFoo(x=1, y=2)
Error in .local(x, y, ...) : object 'do.both' not found
do.both
修复它的冗余声明
setMethod(
f="testFoo",
signature=signature(x="numeric", y="numeric"),
definition=function(
x,
y,
do.both=FALSE
) {
if (do.both) {
out <- list(x=x, y=y)
} else {
out <- x
}
return(out)
}
)
> testFoo(x=1, y=2)
[1] 1