R 中 S4 class 的一元加号
Unary plus for S4 class in R
我正在 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
是否可以重载一元加号?如果是这样,对于这个最小的示例我将如何做?
尝试添加这个(除了你的二进制重载):
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
、
[...] when a unary operator is encountered the Ops method is called
with one argument and e2 is missing.
正如 Frank 指出的那样,?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.
我正在 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
是否可以重载一元加号?如果是这样,对于这个最小的示例我将如何做?
尝试添加这个(除了你的二进制重载):
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
、
[...] when a unary operator is encountered the Ops method is called with one argument and e2 is missing.
正如 Frank 指出的那样,?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.