【问题标题】:Proper way to use cbind, rbind with s4 classes in package在包中使用 cbind、rbind 和 s4 类的正确方法
【发布时间】:2015-01-11 11:30:59
【问题描述】:

我使用 S4 类编写了一个包,并希望将函数 rbind、cbind 与这些定义的类一起使用。

由于似乎无法将rbindcbind 直接定义为S4 方法,因此我改为定义rbind2cbind2

setMethod("rbind2", signature(x="ClassA", y = "ANY"), 
    function(x, y) {
      # Do stuff ...
})

setMethod("cbind2", signature(x="ClassA", y = "ANY"), 
    function(x, y) {
      # Do stuff ...
})

?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)
}

这按预期工作。但是,运行 R CMD check 我现在收到以下注释,因为我在方法中使用了未导出的函数:

* 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.

如何摆脱 NOTE 以及在包中为 S4 类定义方法 cbind 和 rbind 的正确方法是什么?

【问题讨论】:

  • 您是否介意包括您尝试为其添加rbindcbind 方法的几个S4 类的类定义(例如setClass("ClassA",...))?这样可以更轻松地为您的问题找到解决方案。
  • 在这种情况下,类定义并不重要,因为它只是方法选择/调度的问题。所以你可以使用任何定义,比如 setClass("ClassA",representation(a = "numeric"))。
  • 另外,您能否解释一下为什么“...似乎无法将 rbind 和 cbind 直接定义为 S4 方法...” - 也许添加您的试图实现这个的代码?
  • 正如 Matrix 库中 cBind 的帮助页面中所述:基函数 cbind 和 rbind 是为任意数量的参数定义的,因此具有第一个形式参数 .... 因此,无法轻松定义 S4 方法来将继承自 Matrix 的矩阵绑定在一起。

标签: r package s4


【解决方案1】:

我认为基本上 Matrix 包中的 cBind 帮助页面在历史上是准确的,但不是最近。这是一堂课

.A = setClass("A", representation(x="numeric"))

没有泛型,所以创建一个,在 '...' 参数上调度(参见 ?setMethod?dotsMethods

getGeneric("cbind")
## NULL
setGeneric("cbind", signature="...")
## Creating a new generic function for 'cbind' in the global environment

然后实现一个方法

setMethod("cbind", "A", function(..., deparse.level=1) "cbind,A-method")
## [1] "cbind"

最后使用它

> cbind(.A(), .A())
[1] "cbind,A-method"

只要“...”参数是相同的(可能是派生的)类就可以了,这通常足够好。

> cbind(.A(), integer())
     [,1]
[1,] ?  

我相信bind_activation() 具有全局影响,而不仅仅是在您的包裹中发送;应该避免它(例如,它不再在 Matrix 包中使用)。

另外,我认为这已经在 R-devel 中更新了


r67699 |劳伦斯 | 2015-02-01 10:13:23 -0800(2015 年 2 月 1 日,星期日)| 4 线条

cbind/rbind 现在递归地委托给 cbind2 (rbind2) 时至少 一个参数是 S4 对象,S3 调度失败;也考虑S4 *bind 函数中 S3 调度期间的继承。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-11
    • 2011-05-22
    • 2014-04-13
    • 2018-06-06
    • 2017-02-17
    • 1970-01-01
    • 2011-11-13
    • 1970-01-01
    相关资源
    最近更新 更多