R 分派参数';s从S4泛型函数到其关联方法的默认值
假设与特定S4泛型函数/方法关联的所有S4方法共享一个形式参数,该参数应具有特定的默认值。直觉上,我会在S4泛型的定义中陈述这样一个论点(而不是在每个方法定义中陈述它,这对我来说似乎有些多余) 但是,我注意到,这样我会遇到麻烦,因为似乎形式参数的默认值没有发送到方法,因此会抛出错误 这不是有点违背了将泛型和方法结合起来的想法吗?当默认值始终相同时,为什么我必须在每个方法中分别声明形式参数?我能以某种方式显式地分派形式参数的默认值吗R 分派参数';s从S4泛型函数到其关联方法的默认值,r,methods,default-value,s4,R,Methods,Default Value,S4,假设与特定S4泛型函数/方法关联的所有S4方法共享一个形式参数,该参数应具有特定的默认值。直觉上,我会在S4泛型的定义中陈述这样一个论点(而不是在每个方法定义中陈述它,这对我来说似乎有些多余) 但是,我注意到,这样我会遇到麻烦,因为似乎形式参数的默认值没有发送到方法,因此会抛出错误 这不是有点违背了将泛型和方法结合起来的想法吗?当默认值始终相同时,为什么我必须在每个方法中分别声明形式参数?我能以某种方式显式地分派形式参数的默认值吗 下面你会发现一个简短的行为说明 泛型函数 方法 do的冗余语句
下面你会发现一个简短的行为说明 泛型函数 方法
do的冗余语句。两者都修复了它
setMethod(
f=“testFoo”,
签名=签名(x=“数字”,y=“数字”),
定义=功能(
x,,
Y
do.two=FALSE
) {
如果(都做){
out当您调用testFoo(x=1,y=2)
时,它首先由S4泛型处理,它查找一个方法,找到它,并向它发送一个如下所示的调用:testFoo(x=1,y=2,do.both=FALSE,…)
用?standardGeneric
的话来说:
“standardGeneric”分派为泛型定义的方法
名为“f”的函数,使用来自
这就是所谓的
如果它向其分派该调用的方法没有采用do.two
参数,则该方法--就像任何其他R函数一样抛出错误。除非函数定义包含(a)形式参数foo
或(b)a,否则任何函数都不能处理包含参数foo
的调用“dots”参数,…
,可以吸收任意提供的参数
基本上,您所尝试的与以下内容没有什么不同,它们以类似的方式失败,但可能更容易看到:
testFooGeneric <- function(x=1, y=2, do.both=FALSE, ...) {
## The line below does essentially what standardGeneric() does
if(is.numeric(x) & is.numeric(y)) {
testFooMethod(x=x, y=y, do.both=do.both)
}
}
testFooMethod <- function(x, y) {
cat("Success!\n")
}
testFooGeneric(x=1, y=2)
# Error in testFooMethod(x = x, y = y, do.both = do.both) :
# unused argument(s) (do.both = do.both)
太好了,这真的很有道理!这个“…论点正是我需要的。非常感谢,你帮我避免了明天早上大量的复制和粘贴工作!;-)
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
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
testFooGeneric <- function(x=1, y=2, do.both=FALSE, ...) {
## The line below does essentially what standardGeneric() does
if(is.numeric(x) & is.numeric(y)) {
testFooMethod(x=x, y=y, do.both=do.both)
}
}
testFooMethod <- function(x, y) {
cat("Success!\n")
}
testFooGeneric(x=1, y=2)
# Error in testFooMethod(x = x, y = y, do.both = do.both) :
# unused argument(s) (do.both = do.both)
## Option 1
testFooMethod <- function(x, y, do.both) {
cat("Success!\n")
}
testFooGeneric(x=1, y=2)
# Success!
## Option 2
testFooMethod <- function(x, y, ...) {
cat("Success!\n")
}
testFooGeneric(x=1, y=2)
## Success!