【发布时间】:2013-04-02 09:22:31
【问题描述】:
有人可以解释为什么在注册的旧式 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
【问题讨论】:
-
这几乎肯定是这个 [stackoverflow.com/questions/55019663/… 问题背后的相同问题(对象本身需要是 S4,在
isS4()的意义上,至少其中一个需要是 TRUE,并且setOldClass是不够的)。