gpt4 book ai didi

r - R中S4类的一元加

转载 作者:行者123 更新时间:2023-12-04 14:57:08 26 4
gpt4 key购买 nike

我正在 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.



正如弗兰克指出的那样, ?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 - R中S4类的一元加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33548341/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com