gpt4 book ai didi

r - 将参数的默认值从 S4 泛型函数分派(dispatch)到其关联方法

转载 作者:行者123 更新时间:2023-12-01 17:59:21 26 4
gpt4 key购买 nike

假设与特定 S4 通用函数/方法关联的所有 S4 方法共享一个应该具有特定默认值的形式参数。直觉上,我会在 S4 generic 的定义中陈述这样的论点(而不是在每个方法定义中陈述它,这对我来说似乎有点多余)。

但是,我注意到这样我遇到了麻烦,因为形式参数的默认值似乎没有分派(dispatch)给方法,因此引发了错误。

这是否有点违背泛型和方法组合的想法?当默认值始终相同时,为什么我必须再次单独声明每个方法中的形式参数?我可以以某种方式显式分配形式参数的默认值吗?

<小时/>

下面是该行为的简短说明

通用函数

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

最佳答案

当您调用 testFoo(x=1, y=2) 时,它首先由 S4 泛型处理,它会查找方法,找到它,然后向其分派(dispatch)一个调用,该调用看起来像这样:testFoo(x=1, y=2, do.both=FALSE, ...)

?standardGeneric的话来说:

‘standardGeneric’ dispatches the method defined for a generic function named ‘f’, using the actual arguments in the frame from which it is called.

如果它分派(dispatch)该调用的方法不采用 do.both 参数,则该方法 --- 就像任何其他 R 函数一样 --- 抛出错误。任何函数都不能处理包含参数 foo 的调用,除非它的函数定义包含 (a) 形式参数 foo 或 (b) “点”参数 ...,它可以吸收任意提供的参数。

基本上,您所尝试的与以下内容没有什么不同,它以类似但可能更容易看到的方式失败:

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)

要解决上述问题,您需要通过以下两种方式之一重新定义 testFooMethod(),其中任何一种也可以修复您的 S4 方法:

## 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!

关于r - 将参数的默认值从 S4 泛型函数分派(dispatch)到其关联方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12484977/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com