我在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
是否有可能超載一元加號?如果是這樣,我將如何做這個最小的例子?
太棒了!謝謝你解決我的問題! – Gumeo
我認爲'?setMethod'也很有用,它解釋瞭如何指示一個arg丟失,比如''missing',這意味着這個參數不能出現在調用中以匹配這個簽名。' – Frank
好的,這個爲我澄清!謝謝很多傢伙:) – Gumeo