基矩阵类下标操作符的R S4重载

您所在的位置:网站首页 下标的下标 基矩阵类下标操作符的R S4重载

基矩阵类下标操作符的R S4重载

2023-04-02 17:41| 来源: 网络整理| 查看: 265

我以这种方式定义了一个名为FilterCommand dIndices的S4类:

setClass('FilterCommandIndices', representation(rows='logical', cols='logical') )

它只包含两个插槽,逻辑向量指示给定的行或列是否包含在集合中。然后我想重载下标操作符以使其与前一个类一起使用。我的初始实现是这样的:

setMethod('[', c(x='ANY', i='FilterCommandIndices', j='missing'), function(x, i, j, ..., drop=TRUE) { if (nrow(x) != length(getRows(i)) || ncol(x) != length(getCols(i))) { stop('Incorrect number of dimensions') } else { return(x[getRows(i), getCols(i)]) } })

在前面的代码中,getRow()和getCols()是FilterCommand dIndices类的相应微不足道的访问器:

setGeneric('getRows', function(object) standardGeneric('getRows')) setMethod('getRows', 'FilterCommandIndices', function(object) { return(object@rows) }) setGeneric('getCols', function(object) standardGeneric('getCols')) setMethod('getCols', 'FilterCommandIndices', function(object) { return(object@cols) })

我认为通过使用ANY签名,我可以使这个简单的类和运算符组合即使在基类中也能工作,就像一个简单的矩阵一样。虽然它似乎适用于示例类…

d> bar1 An object of class "FilterCommandIndices" Slot "rows": [1] FALSE TRUE TRUE TRUE TRUE Slot "cols": [1] TRUE TRUE TRUE TRUE TRUE d> mockMethylSet MethylSet (storageMode: lockedEnvironment) assayData: 5 features, 5 samples element names: Meth, Unmeth phenoData: none Annotation Preprocessing Method: unknown minfi version: unknown Manifest version: unknown d> mockMethylSet[bar1] MethylSet (storageMode: lockedEnvironment) assayData: 4 features, 5 samples element names: Meth, Unmeth phenoData: none Annotation Preprocessing Method: unknown minfi version: unknown Manifest version: unknown

…但不在基矩阵类中:

d> zeroDetectionP S1 S2 S3 S4 S5 F1 0 0 0 0 0 F2 0 0 0 0 0 F3 0 0 0 0 0 F4 0 0 0 0 0 F5 0 0 0 0 0 d> zeroDetectionP[bar1] Error en zeroDetectionP[bar1] : invalid subscript type 'S4'

在setMethod文档中,它说你可以在签名中使用基类来定义方法,这让我认为我可以使用ANY签名来实现类似于之前方法的东西,并且只有当下标对象没有实现nrow()、nco()或运算符'['时才会失败。

任何帮助或提示将不胜感激。

更新:设置特定的签名方法(如@hadley建议的)

如果我为矩阵基类设置一个具有特定签名的方法…

d> getMethod('[', c(x='matrix', i='FilterCommandIndices', j='missing')) Method Definition: function (x, i, j, ..., drop = TRUE) { return(x) # Dummy method }

…然后再次尝试下标矩阵…

d> zeroDetectionP[bar1] Error en zeroDetectionP[bar1] : invalid subscript type 'S4'

…错误仍然存在。

更新:最小可重现示例

我试图写一个最小的场景,我可以重现以前的场景。我认为,这是一个给出相同错误的简单场景。正如@hadley所建议的,这可能是由于下标是原语。

library(methods) setClass('Indices', representation(rows='logical', cols='logical')) setMethod('[', c(x='ANY', i='Indices', j='missing'), function(x, i, j, ..., drop=FALSE) { return(x[i@rows, i@cols]) }) setClass('M', representation(m='matrix')) setMethod('[', c(x='M', i='logical', j='logical'), function(x, i, j, ..., drop=FALSE) { return(x@m[i, j]) }) anIndicesObject


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3