【发布时间】:2012-08-23 22:25:16
【问题描述】:
什么是定义通用函数的好方法,它应该具有 S3 和 S4 类的实现?我一直在使用这样的东西:
setGeneric("myfun", function(x, ...){
standardGeneric("myfun");
});
setMethod("myfun", "ANY", function(x, ...) {
if(!isS4(x)) {
return(UseMethod("myfun"));
}
stop("No implementation found for class: ", class(x));
});
这成功了:
myfun.bar <- function(x, ...){
return("Object of class bar successfully dispatched.");
}
object <- structure(123, class=c("foo", "bar"));
myfun(object)
是否有移动“本地”方式来完成此任务?我知道我们可以使用setOldClass 为 S3 类定义 S4 方法,但是这样我们就失去了 S3 方法的调度,以防一个对象有多个类。例如。 (在干净的会话中):
setGeneric("myfun", function(x, ...){
standardGeneric("myfun");
});
setOldClass("bar")
setMethod("myfun", "bar", function(x, ...){
return("Object of class bar successfully dispatched.");
});
object <- structure(123, class=c("foo", "bar"));
myfun(object)
这失败了,因为object 的第二类,在本例中为bar,被忽略了。我们可以通过在foo 和bar 之间定义正式的S4 继承来解决这个问题,但是对于我的应用程序,我更希望myfun.bar 能够在具有bar 类的S3 对象上开箱即用。
不管怎样,事情变得一团糟,我想这是一个常见的问题,所以可能有更好的方法来做到这一点?
【问题讨论】:
-
另请参阅stackoverflow.com/questions/12709933/…,了解将 S4 调度添加到基础 R 中的 S3 泛型的特殊情况。