R S4 class 联合 class 联合

R S4 class union of class unions

我正在尝试建立一个由 class 个联合组成的联合,以促进方法分派。以下 reprex 在全局环境中执行时完全符合我的要求,但是一旦我将此代码放入包中,最后一行 f(new("a")) 就会抛出无法找到继承方法的错误。

setClass("x", slots = list(slot ="character"))
setClass("y", slots = list(slot ="character"))
setClass("a", slots = list(slot ="character"))
setClass("b", slots = list(slot ="character"))
setClassUnion("xy", c("x", "y"))
setClassUnion("ab", c("a", "b"))
setClassUnion("xyab", c("xy", "ab"))
setGeneric("f", function(object, ...) standardGeneric("f"))
setMethod("f", "xyab", function(object, ...) print("hi!"))

## print's "hi!" as expected
f(new("a"))

我错过了什么?

为了便于在新的 R 会话中重现,这里重现了问题:

library(devtools)
fn <- "codefile.R"
writeLines(
    c(
        "setClass('x', slots = list(slot ='character'))",
        "setClass('y', slots = list(slot ='character'))",
        "setClass('a', slots = list(slot ='character'))",
        "setClass('b', slots = list(slot ='character'))",
        "setClassUnion('xy', c('x', 'y'))",
        "setClassUnion('ab', c('a', 'b'))",
        "setClassUnion('xyab', c('xy', 'ab'))",
        "setGeneric('f', function(object, ...) standardGeneric('f'))",
        "setMethod('f', 'xyab', function(object, ...) print('hi!'))"
    ),
    con = fn
)

package.skeleton(code_files = "codefile.R")
devtools::load_all("anRpackage")
f(new("a"))

根据 R-devel,这已在 4.0 中得到解决:

https://r.789695.n4.nabble.com/Possible-Regression-in-setClassUnion-between-3-5-0-and-3-6-0-td4761507.html