这是 Using callNextMethod() within accessor function in R 的扩展.
2017 年 3 月 25 日更新:为了说明这仅在加载方法时失败,而不是在构建包中时失败,我创建了一个虚拟包:https://github.com/zkamvar/inheritest#readme
基本问题:
我有一个继承另一个类 foo 的类 bar,并且它们都有 [ 方法的附加参数。 foo 的方法一直有效,但 bar 的方法在第一次使用后失败。
错误和追溯:
Error in callNextMethod(x, i, j, ..., drop): bad object found as method (class "function")
4: stop(gettextf("bad object found as method (class %s)", dQuote(class(method))),
domain = NA)
3: callNextMethod(x, i, j, ..., drop) at #9
2: .local(x, i, j, ..., drop = drop)
1: BAR["x"]
更多细节:
我有一个包,它实现了一个依赖于另一个包中的类的类。构建包后,一切正常,但是当我的包被简单加载时(使用
devtools::load_all(".")
),我得到以下行为。最小工作示例:
foo <- setClass("foo", representation(x = "numeric", y = "numeric"))
bar <- setClass("bar", representation(distance = "numeric"), contains = "foo")
setMethod(f = "[", signature = signature(x = "foo", i = "ANY", j = "ANY", drop = "ANY"),
definition = function(x, i, j, ..., foo = TRUE, drop = FALSE) {
if (foo)
message("FOOOOOOO")
if (i == "x") {
return(x@x)
} else {
if (i == "y") {
return(x@y)
}
}
})
#> [1] "["
setMethod(f = "[", signature = signature(x = "bar", i = "ANY", j = "ANY", drop = "ANY"),
definition = function(x, i, j, ..., bar = TRUE, drop = FALSE) {
if (bar)
message("BAAAAAAR")
if (i == "distance") {
return(x@distance)
} else {
callNextMethod(x, i, j, ..., drop)
}
})
#> [1] "["
FOO <- new("foo", x = 1, y = 4)
BAR <- new("bar", x = 1, y = 4, distance = 3)
FOO["x"]
#> FOOOOOOO
#> [1] 1
BAR["x"]
#> BAAAAAAR
#> FOOOOOOO
#> [1] 1
FOO["x"]
#> FOOOOOOO
#> [1] 1
BAR["distance"]
#> BAAAAAAR
#> [1] 3
BAR["x"] # fails
#> BAAAAAAR
#> Error in callNextMethod(x, i, j, ..., drop): bad object found as method (class "function")
BAR["x", foo = FALSE]
#> BAAAAAAR
#> [1] 1
注意:当我通过 reprex 时, 对 BAR 的第一次和最后一次调用也导致错误,但我正在展示我在交互式 session 中的体验。我正在使用 R 版本 3.3.3
最佳答案
这是因为 callNextMethod()
不够聪明,无法处理具有增强形式的原语方法。我已经修复了它,很快就会提交到后备箱。
关于r - 带有附加参数的 S4 类 [(子集)继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42894213/