Max*_*nce 6 inheritance r argument-passing s4
这与以下帖子在R中传递带有callNextMethod()的参数有关
我正在编写两个S4类的访问器,'foo'和'bar'.'bar'继承自foo,仅延伸几个插槽.我没有为类'bar'的对象编写完整的访问函数,而是在访问'foo'继承的插槽时将参数传递给callNextMethod().我的代码看起来像这样:
foo <- setClass("foo", representation(x = "numeric", y = "numeric"))
bar <- setClass("bar", representation(distance = "numeric"), contains = "foo")
setMethod("[", "bar", function(x, i, j, drop) {
if (i == "distance") {
return(x@distance)
} else {
callNextMethod()
}
}
)
setMethod("[", "foo", function(x, i, j, drop) {
if (i == "x") {
return(x@x)
} else {
if (i == "y") {
return(x@y)
}
}
}
)
Run Code Online (Sandbox Code Playgroud)
现在让我们试试这个:
f <- new("foo", x = 1, y = 2)
b <- new("bar", x = 3, y = 4, distance = 5)
f["x"]
f["y"]
Run Code Online (Sandbox Code Playgroud)
类'foo'的对象'f'的访问器正确返回:
> f["x"]
[1] 1
> f["y"]
[1] 2
Run Code Online (Sandbox Code Playgroud)
如果我尝试访问"bar"类对象"b"的插槽"距离",则访问者也会正确返回:
> b["distance"]
[1] 5
Run Code Online (Sandbox Code Playgroud)
当我尝试访问继承自'foo'的类'bar'的对象'b'的任何插槽时,会出现问题.如果我尝试:
b["x"]
b["y"]
Run Code Online (Sandbox Code Playgroud)
我收到以下错误消息:
Error in callNextMethod() : bad object found as method (class “function”)
Run Code Online (Sandbox Code Playgroud)
我已经阅读了这篇文章中的建议在R中使用callNextMethod()传递参数的问题,但我无法为'['定义泛型,并且尝试将参数显式传递给callNextMethod()也失败了.
当然我做错了!我已经阅读了几个关于遗产的资源,无法确定问题,我希望大家能指导我朝着正确的方向前进.
谢谢
马克斯
你的方法都[省略了任何方法所需的五个形式参数之一,即省略号(...).
args(getGeneric("["))
# function (x, i, j, ..., drop = TRUE)
# NULL
Run Code Online (Sandbox Code Playgroud)
在两种方法定义中将其作为正式包含解决了您的问题:
setMethod("[", "bar", function(x, i, j, ..., drop) {
if (i == "distance") {
return(x@distance)
} else {
callNextMethod()
}
}
)
setMethod("[", "foo", function(x, i, j, ..., drop) {
if (i == "x") {
return(x@x)
} else {
if (i == "y") {
return(x@y)
}
}
}
)
b["distance"]
# [1] 5
b["x"]
# [1] 3
b["y"]
# [1] 4
Run Code Online (Sandbox Code Playgroud)