定义一个应该具有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. …
我有两个类(a和b),我想+为它们定义方法.我需要两种类的四种可能组合的不同方法,即:
a + a method 1
a + b method 2
b + a method 3
b + b method 4
Run Code Online (Sandbox Code Playgroud)
我知道我可以使用S4进行多次调度,但我想知道是否有办法使用S3模拟这种行为.我的方法如下:
a <- "b"
class(a) <- "a"
b <- "e"
class(b) <- "b"
Ops.a <- function(e1, e2){
if (class(e1) == "a" &
class(e2) == "a")
print("a & a")
if (class(e1) == "a" &
class(e2) == "b")
print("a & b")
if (class(e1) == "b" &
class(e2) == "a")
print("b & a")
NULL
}
a …Run Code Online (Sandbox Code Playgroud) 我一直在研究这个相当古老的问题并且玩弄不同的功能和类.从下面可以看出,单次调用setGeneric可以产生一些我以前从未见过的符号.
setGeneric("+", function(e1, e2) standardGeneric("+"),
useAsDefault=base::`+`)
#Creating a new generic function for ‘+’ in the global environment
#[1] "+"
1 + 1
#`__Deferred_Default_Marker__`
Run Code Online (Sandbox Code Playgroud)
那么,"__ Deferred_Default_Marker__"是什么意思呢?这是"错误"还是某种"未定义的行为"?FWIW,再次rm("+")恢复运营商.1 + 12