我无法找出定义 [
的正确方法, $
, 和 [[
S4 类的子集运算符。
任何人都可以为我提供一个为 S4 类定义这三个的基本示例吗?
最佳答案
发现泛型,以便我们知道我们的目标
> 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
调用一个方法来完成类的子集化工作。[[
没有概念上的差异,除了想要尊重返回内容的语义而不是像 [
暗示的另一个对象实例.对于 $
我们有> 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
关于oop - 如何定义 S4 类的子集运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10961842/