2015-11-05 63 views
6

我在R中試驗S4類,我試圖爲我的對象定義一個加號(+)運算符,即超載加運算符。我設法超載二進制+,但我不知道如何超載一元加。下面是一個最小的工作(元運算符不工作)例如什麼,我想實現: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([email protected]," + ",[email protected])) 
      } 
) 

現在我可以使用+子及工程進展順利:

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("+ ",[email protected])) 
      } 
) 

但這生成錯誤:

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

是否有可能超載一元加號?如果是這樣,我將如何做這個最小的例子?

回答

6

嘗試加入這個(除了你的二進制過載):

setMethod("+", signature(e1 = "HWtest", e2 = "missing"), 
      function(e1){ 
      new("HWtest", 
       expr = paste("+ ", [email protected])) 
      } 
) 

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

[...] when a unary operator is encountered the Ops method is called with one argument and e2 is missing.

正如弗蘭克指出,?setMethod幫助文件包含一些有關使用missing作爲方法簽名(強調增加)的一些有用信息:

Two additional special class names can appear: "ANY", meaning that this argument can have any class at all; and "missing", meaning that this argument must not appear in the call in order to match this signature.

+0

太棒了!謝謝你解決我的問題! – Gumeo

+2

我認爲'?setMethod'也很有用,它解釋瞭如何指示一個arg丟失,比如''missing',這意味着這個參數不能出現在調用中以匹配這個簽名。' – Frank

+0

好的,這個爲我澄清!謝謝很多傢伙:) – Gumeo