问题描述
我正在尝试将现有的 S3 对象扩展到 S4,以便更好地控制使用 +
运算符的分派。在基本情况下,e1
和 e2
通常会从同一个类继承,但目标是让调度调用 S4 方法。下面的代码是我试图显示错误。
假设我们有两个 S3 类 a
和 b
,它们有自己的 +
方法。
a <- function(x) structure(x,class = "a")
"+.a" <- function(e1,e2) cat("+.a method\n")
a(1) + 1
#+.a method
b <- function(x) structure(x,class = "b")
"+.b" <- function(e1,e2) cat("+.b method\n")
b(1) + 1
#+.a method
这两个类不能加在一起,因为它们没有定义了 +
方法的共享类
a(1)+b("")
#Error in a(1) + b("") : non-numeric argument to binary operator
#In addition: Warning message:
#Incompatible methods ("+.a","+.b") for "+"
所以,我的下一步是看看我是否可以在 S4 中解决这个问题。我首先设置旧的 S3 类并创建一个新的 S4 以进行扩展。
setoldClass("a")
setoldClass("b")
setClass("B",contains = c("b","a"))
现在使用 +
方法测试 S4:
setMethod("+",signature("B","a"),function(e1,e2) cat("B,a S4 Method"))
new("B") + 1
#+.b method #expected to default to +.b as no S4 signature defined for "B","numeric"
new("B") + a(1)
#B,a S4 Method #Also expected result
new("B") + new("B")
#B,a S4 Method #Also expected result
到目前为止,一切都按预期进行。当 S3 对象具有多重继承时,会发生意外的调度调用(在我看来)。
ab <- structure(1,class = c("a","b"))
ba <- structure(1,class = c("b","a"))
ca <- structure(1,class = c("c","a"))
cab <- structure(1,"a","b"))
new("B") + ab
#B,a S4 Method
new("B") + ba
#+.b method
new("B") + ca
#Error in new("B") + ca : non-numeric argument to binary operator
#In addition: Warning message:
#Incompatible methods ("+.b","+.a") for "+"
new("B") + cab
#Error in new("B") + cab : non-numeric argument to binary operator
#In addition: Warning message:
#Incompatible methods ("+.b","+.a") for "+"
我希望 S4 调度以下列方式检查签名:
signature("B","c") # Failed: no method
signature("B","a") # Method Exists
相反,它似乎是这样检查的:
signature("B","c") # Failed: no method
signature("b","a") # Methods Exists --- But they are incompatible
我知道我可以为 signature("B","c")
创建一个方法,但问题是我可能不知道 e2
上可能存在什么新类,这就是为什么我想在共享的a
的类,因为所有对象都将从这个类继承,S4 或 S3。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)