这是Hadley的高级R书中的一个例子:
setGeneric("type", function(x) standardGeneric("type"))
setMethod("type", signature("matrix"), function(x) "matrix")
setMethod("type", signature("character"), function(x) "character")
type(letters)
type(matrix(letters, ncol = 2))
foo <- structure(list(x = 1), class = "foo")
type(foo)
setOldClass("foo")
setMethod("type", signature("foo"), function(x) "foo")
type(foo)
setMethod("+", signature(e1 = "foo", e2 = "numeric"), function(e1, e2) {
structure(list(x = e1$x + e2), class = "foo")
})
foo + 3
除了最后一行外,一切都如预期一样工作,这在R 3.1.3中引起了一个错误:
Error in foo + 3 : non-numeric argument to binary operator
知道发生了什么事吗?
这个问题是由S3和S4类系统之间的混淆引起的。foo
是一个S3类(它是用setOldClass
而不是setClass
创建的),所以当用它作为第一个参数调用+
时,它会尝试S3方法调度(寻找一个名为+.foo
的函数)。这就是为什么评论中关于定义这样一个函数的建议解决了这个问题。
如果foo
是一个"纯S4"类(即它有槽并且是通过setClass
创建的),那么您的代码就可以工作了。