S4中的substitute()函数

4

如果一个S4通用函数的命名参数只在方法中定义,那么substitute()将按预期工作:

> setGeneric("fS4", function(x, ...) standardGeneric("fS4"))
> setMethod("fS4", signature("numeric"),
+     function(x, ...) deparse(substitute(x))
+ )
[1] "fS4"
> fS4(iris[,1])
[1] "iris[, 1]"

然而,如果在方法定义中添加一个额外的命名参数,substitute() 将不再正确地将该参数作为传递的值返回:

> setMethod("fS4", signature("numeric"),
+     function(x, y, ...) deparse(substitute(x))
+ )
[1] "fS4"
> fS4(iris[,1])
[1] "x"

有什么线索可以说明为什么会出现这种情况,最重要的是,如何绕过此问题?
1个回答

3
请看:

请看

showMethods(fS4, includeDef=TRUE)

显示的是
Function: fS4 (package .GlobalEnv)
x="numeric"
function (x, ...) 
{
    .local <- function (x, y, ...) 
    deparse(substitute(x))
    .local(x, ...)
}

S4实现与通用方法签名不同的方法的方式是,创建一个具有修改后签名的'.local'函数,该函数位于具有通用签名的函数内部。substitute在错误的环境中进行评估。潜在问题与S4无关。
> f = function(x) deparse(substitute(x))
> g = function(y) f(y)
> f(1)
[1] "1"
> g(1)
[1] "y"
> h = function(...) f(...)
> h(1)
[1] "1"

任何试图在“正确”的环境中进行评估的尝试都将受到用户提供的任意构造的阻挠。


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