R其他物件

示例

在[和[[运营商是是通用的基本功能。这意味着R中的任何对象(特别是-即具有显式的“类”属性)在被子集化时都可以具有其自己的指定行为。即对于和/或具有自己的方法。isTRUE(is.object(x))[[[

例如,这是用“data.frame”的情况下(其中)对象和方法被定义,并且它们制成具有两个“矩阵”状和“列表”般的子集。通过在设置“ data.frame”时强制错误,我们看到实际上在我们-just- use时调用了一个函数。is.object(iris)[.data.frame[[.data.frame[.data.frame[

iris[invalidArgument, ]
## Error in `[.data.frame`(iris, invalidArgument, ) : 
##   object 'invalidArgument' not found

在当前主题上没有进一步细节的情况下,示例[方法:

x = structure(1:5, class = "myClass")
x[c(3, 2, 4)]
## [1] 3 2 4
'[.myClass' = function(x, i) cat(sprintf("We'd expect '%s[%s]' to be returned but this a custom `[` method and should have a `?[.myClass` help page for its behaviour\n", deparse(substitute(x)), deparse(substitute(i))))

x[c(3, 2, 4)]
## We'd expect 'x[c(3, 2, 4)]' to be returned but this a custom `[` method and should have a `?[.myClass` help page for its behaviour
## NULL

[通过使用等效的非泛型.subset(和.subset2for [[),我们可以克服方法的调度。这在编程我们自己的“类”时特别有用且高效,并且在有效地对“类”unclass(x)进行计算(避免方法分派和复制对象)时希望避免变通方法(例如):

.subset(x, c(3, 2, 4))
## [1] 3 2 4