如何为S4类定义子集运算符? [英] How to define the subset operators for a S4 class?
问题描述
我很难为S4类定义正确的方法来定义[
,$
和[[
子集运算符.
I am having trouble figuring out the proper way to define the [
, $
, and [[
subset operators for an S4 class.
谁能为我提供一个为S4类定义这三个的基本示例?
Can anyone provide me with a basic example of defining these three for an S4 class?
推荐答案
发现通用名称,以便我们了解我们的目标
Discover the generic so that we know what we are aiming for
> getGeneric("[")
standardGeneric for "[" defined from package "base"
function (x, i, j, ..., drop = TRUE)
standardGeneric("[", .Primitive("["))
<bytecode: 0x32e25c8>
<environment: 0x32d7a50>
Methods may be defined for arguments: x, i, j, drop
Use showMethods("[") for currently available ones.
定义一个简单的类
setClass("A", representation=representation(slt="numeric"))
并实现方法
setMethod("[", c("A", "integer", "missing", "ANY"),
## we won't support subsetting on j; dispatching on 'drop' doesn't
## make sense (to me), so in rebellion we'll quietly ignore it.
function(x, i, j, ..., drop=TRUE)
{
## less clever: update slot, return instance
## x@slt = x@slt[i]
## x
## clever: by default initialize is a copy constructor, too
initialize(x, slt=x@slt[i])
})
实际情况:
> a = new("A", slt=1:5)
> a[3:1]
An object of class "A"
Slot "slt":
[1] 3 2 1
有多种支持(隐式)签名的策略,例如,您可能还希望支持逻辑索引和字符索引值,可能同时适用于i和j.最直接的是外观"模式,其中每种方法对子集索引的常见类型(例如integer
)进行某种初步强制,以允许对索引条目进行重新排序和重复,然后使用callGeneric
进行调用一个方法完成子类的工作.
There are different strategies for supporting the (implicitly) many signatures, for instance you'd likely also want to support logical and character index values, possibly for both i and j. The most straight-forward is a "facade" pattern where each method does some preliminary coercion to a common type of subset index, e.g., integer
to allow for re-ordering and repetition of index entries, and then uses callGeneric
to invoke a single method that does the work of subsetting the class.
[[
没有概念上的区别,只是希望尊重返回内容的语义,而不是[
所隐含的对象的另一个实例.对于$
,我们有
There are no conceptual differences for [[
, other than wanting to respect the semantics of returning the content rather than another instance of the object as implied by [
. For $
we have
> getGeneric("$")
standardGeneric for "$" defined from package "base"
function (x, name)
standardGeneric("$", .Primitive("$"))
<bytecode: 0x31fce40>
<environment: 0x31f12b8>
Methods may be defined for arguments: x
Use showMethods("$") for currently available ones.
和
setMethod("$", "A",
function(x, name)
{
## 'name' is a character(1)
slot(x, name)
})
使用
> a$slt
[1] 1 2 3 4 5
这篇关于如何为S4类定义子集运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!