相关疑难解决方法(0)

在单个函数中组合S4和S3方法

定义一个应该具有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));
});
Run Code Online (Sandbox Code Playgroud)

这成功了:

myfun.bar <- function(x, ...){
    return("Object of class bar successfully dispatched.");
}
object <- structure(123, class=c("foo", "bar"));
myfun(object)
Run Code Online (Sandbox Code Playgroud)

是否有一种"原生"方式来实现这一目标?我知道我们可以使用S3类定义S4方法setOldClass,但是这样我们就失去了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)
Run Code Online (Sandbox Code Playgroud)

这会失败,因为object在这种情况下bar,第二类被忽略.我们可以通过在foo和之间定义正式的S4继承来解决这个问题bar,但是对于我的应用程序,我宁愿myfun.bar在一个类的S3对象上开箱即用bar. …

r cran s4

13
推荐指数
1
解决办法
1326
查看次数

标签 统计

cran ×1

r ×1

s4 ×1