【问题标题】:substitute() in S4S4 中的替换()
【发布时间】:2012-11-22 17:39:27
【问题描述】:

如果在方法中只定义了 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"

关于为什么会发生这种情况以及最重要的是如何解决它的任何线索?

【问题讨论】:

    标签: r s4


    【解决方案1】:

    看看

    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"
    

    并且任何在“正确”环境中进行评估的尝试都会被用户提供的任意构造所阻挠。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多