我已经使用S4类编写了一个包,并希望使用函数rbind,cbind和这些定义的类.
因为似乎不可能直接定义rbind和定义cbind为我定义的S4方法rbind2,cbind2而是:
setMethod("rbind2", signature(x="ClassA", y = "ANY"),
function(x, y) {
# Do stuff ...
})
setMethod("cbind2", signature(x="ClassA", y = "ANY"),
function(x, y) {
# Do stuff ...
})
Run Code Online (Sandbox Code Playgroud)
从?cbind2我了解到,需要激活这些函数来methods:::bind_activation从base替换rbind和cbind.
我使用以下.onLoad函数将调用包含在包文件R/zzz.R中:
.onLoad <- function(...) {
# Bind activation of cbind(2) and rbind(2) for S4 classes
methods:::bind_activation(TRUE)
}
Run Code Online (Sandbox Code Playgroud)
这按预期工作.但是,运行R CMD检查我现在得到以下注释,因为我在方法中使用了未导出的函数:
* checking dependencies in R code ... NOTE
Unexported object imported by a ':::' call: 'methods:::bind_activation'
See the note in ?`:::` about the use of this operator.
Run Code Online (Sandbox Code Playgroud)
如何摆脱NOTE以及为包中的S4类定义方法cbind和rbind的正确方法是什么?
我认为基本上 Matrix 包中的 cBind 帮助页面在历史上是准确的,但最近不是。这里有一个类
.A = setClass("A", representation(x="numeric"))
Run Code Online (Sandbox Code Playgroud)
没有通用的,因此创建一个,根据 '...' 参数进行调度(请参阅?setMethod和?dotsMethods)
getGeneric("cbind")
## NULL
setGeneric("cbind", signature="...")
## Creating a new generic function for 'cbind' in the global environment
Run Code Online (Sandbox Code Playgroud)
然后实现一个方法
setMethod("cbind", "A", function(..., deparse.level=1) "cbind,A-method")
## [1] "cbind"
Run Code Online (Sandbox Code Playgroud)
最后使用它
> cbind(.A(), .A())
[1] "cbind,A-method"
Run Code Online (Sandbox Code Playgroud)
只要“...”参数是相同的(可能是派生的)类就可以了,这通常就足够了。
> cbind(.A(), integer())
[,1]
[1,] ?
Run Code Online (Sandbox Code Playgroud)
我相信这bind_activation()会产生全球性的影响,而不仅仅是对包裹的派送;应该避免它(例如,它不再在 Matrix 包中使用)。
另外,我认为这已经在 R-devel 中更新了
r67699 | 劳伦斯| 2015-02-01 10:13:23 -0800(2015 年 2 月 1 日星期日)| 4行
现在,当至少一个参数是 S4 对象且 S3 调度失败时,cbind/rbind 会递归委托给 cbind2 (rbind2);还要在 *bind 函数中的 S3 分派期间考虑 S4 继承。