r-在S4通用方法中使用S3对象会导致错误

  • 本文关键字:对象 错误 S3 S4 方法 r r-s4
  • 更新时间 :
  • 英文 :


这是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创建的),那么您的代码就可以工作了。

最新更新