【问题标题】:Unary plus for S4 class in RR中S4类的一元加
【发布时间】:2016-02-06 12:15:47
【问题描述】:

我正在 R 中试验 S4 类,我试图为我的对象定义一个加号 (+) 运算符,即重载加号运算符。我设法重载二进制+,但我不知道如何重载一元加号。这是我想要实现的最小工作(一元运算符不工作)示例:

setClass("HWtest",
         representation(expr  = "character"),
         prototype = list(expr  = NA_character_)
)

H <- new("HWtest", expr="Hello")
W <- new("HWtest", expr="World")

setMethod("+", signature(e1="HWtest", e2="HWtest"),
          function(e1,e2){
            new("HWtest", 
                expr = paste(e1@expr," + ",e2@expr))
          }
)

现在我可以使用+ 操作符,并且运行顺畅:

H+W
An object of class "HWtest"
Slot "expr":
[1] "Hello  +  World"

现在一元加号当然不起作用,所以必须重载

+H
Error in +H : invalid argument to unary operator

所以我尝试通过以下方式重载它:

setMethod("+", signature(e="HWtest"),
          function(e){
            new("HWtest", 
                expr = paste("+ ",e@expr))
          }
)

但这会产生错误:

Error in match.call(fun, fcall) : 
  argument 1 matches multiple formal arguments

一元加号可以超载吗?如果是这样,对于这个最小的示例,我将如何做?

【问题讨论】:

    标签: r operator-overloading s4 unary-operator


    【解决方案1】:

    尝试添加这个(除了你的二进制重载):

    setMethod("+", signature(e1 = "HWtest", e2 = "missing"),
              function(e1){
                new("HWtest", 
                    expr = paste("+ ", e1@expr))
              }
    )
    

    R> +H
    An object of class "HWtest"
    Slot "expr":
    [1] "+  Hello"
    
    R> H + W
    An object of class "HWtest"
    Slot "expr":
    [1] "Hello  +  World"
    

    引用帮助文件?groupGeneric

    [...] 当遇到一元运算符时,调用 Ops 方法 有一个参数并且缺少 e2。

    正如弗兰克所指出的,?setMethod 帮助文件包含一些关于使用 missing 作为方法签名的有用信息(已添加重点):

    可以出现两个额外的特殊类名:“ANY”,意思是 这个论点可以有任何类别; 和“失踪”,意思是 此参数不得出现在调用中以匹配此 签名。

    【讨论】:

    • 我认为?setMethod 也很有用,它解释了如何指示缺少一个arg,例如"missing", meaning that this argument must not appear in the call in order to match this signature.
    • 好的,这为我澄清了!非常感谢大家:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    • 2013-01-03
    • 2018-10-01
    • 2011-01-22
    • 2016-05-27
    • 1970-01-01
    相关资源
    最近更新 更多