gpt4 book ai didi

r - 与 S4 类相比,使用 setOldClass 时重载运算符无法按预期工作

转载 作者:行者123 更新时间:2023-12-02 08:34:00 26 4
gpt4 key购买 nike

有人可以解释为什么在注册的旧式 S3 类上重载运算符不能按预期工作,而在定义新类并重载运算符时却可以工作。

如下例所示。

这不起作用。

require(ff) 
setOldClass(Classes=c("ff_vector"))
setMethod(
f="*",
signature = signature(e1 = c("ff_vector"), e2 = c("ff_vector")),
definition = function (e1, e2){
print("S3 setOldClass")
e1[] * e2[]
}
)
ff(1:10) * ff(1:10)
Error in ff(1:10) * ff(1:10) : non-numeric argument to binary operator

但这有效。

setClass("myff_vector", representation(x="ff_vector"))
setMethod(
f="*",
signature = signature(e1 = c("myff_vector"), e2 = c("myff_vector")),
definition = function (e1, e2){
print("S4 setOldClass")
e1@x[] * e2@x[]
}
)
new("myff_vector", x = ff(1:10)) * new("myff_vector", x = ff(1:10))
[1] "S4 setOldClass"
[1] 1 4 9 16 25 36 49 64 81 100

最佳答案

尝试部分答案:在 help('Methods') 的通用函数部分中,指出:

Methods may be defined for most primitives, and corresponding metadata objects will be created to store them. Calls to the primitive still go directly to the C code, which will sometimes check for applicable methods. The definition of “sometimes” is that methods must have been detected for the function in some package loaded in the session and isS4(x) is TRUE for the first argument (or for the second argument, in the case of binary operators).

回到你的问题,* 是一个原语,并且:

library(ff)
setOldClass("ff_vector")
isS4(ff(1:10))
[1] FALSE

因此,据我了解,即使您使用 setOldClass(),也不可能在 S3 类上定义原始函数的方法。

关于r - 与 S4 类相比,使用 setOldClass 时重载运算符无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15927479/

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