在R中调度重载的standardGeneric方法

时间:2015-11-30 02:36:26

标签: r plot overloading s4

考虑以下完整的R示例:

setClass("foo", representation(data = "data.frame"))

if (!isGeneric("plot"))
  setGeneric("plot", function(x, y, ...) standardGeneric("plot"))

setMethod(f = "plot", 
          signature(x = "foo", y = 'missing'),
          definition = function(x, y, ...) {
            plot(data$x, data$y)
          }
)

fooObject = new('foo', data=data.frame(x=rnorm(100), y =rnorm(100)))

绘制对象失败如下:

> plot(fooObject)
Error in as.double(y) : 
  cannot coerce type 'S4' to vector of type 'double'

原因似乎是为S4对象fooObject调用了通用的plot()函数。但是,似乎存在正确的(?)方法。显然,我对“正确”的定义是关闭的。有人可以解释发生了什么吗?

> showMethods('plot')
Function: plot (package graphics)
x="ANY", y="ANY"
x="bootFlexclust", y="missing"
x="color", y="ANY"
x="foo", y="missing"

1 个答案:

答案 0 :(得分:0)

您的问题只是您没有访问对象的插槽。试试这个:

setMethod(f = "plot", 
    signature(x = "foo", y = "missing"),
    definition = function(x, y, ...) {
        slotdata<-x@data
        plot(slotdata$x, slotdata$y)
    }
)

我有一个类似于在包内定义的功能图的问题,继续使用图形标准Generics:

Error in as.double(x) : 
cannot coerce type 'S4' to vector of type 'double'

事实证明,在构建软件包时我忘记了导出它。

相关问题