2014-02-26 13 views
4

我寫了一個S4級,並推翻了「==」 - 運營商,R:重載==和%在%

setMethod("==", 
     signature=c(e1="CAttribute", e2="CAttribute"), 
     definition=function(e1, e2) 
    { 
    return(getName(e1) == getName(e2)) 
    } 
) 

如果我現在要測試是否CAttribute的一個實例是在列表CAttributes,

a1 <- new("CAttribute", name="a1") 
l <- list(new("CAttribute", name="a1"), new("CAttribute", name="a2")) 
a1 %in% l 

我收到以下錯誤

Error in match(x, table, nomatch = 0L) : 
    'match' requires vector arguments 

,該怎麼辦錯了,我怎麼能測試S4對象的列表的的發生特定對象相應於某個「==」 - 運算符?

+0

您沒有向我們展示如何覆蓋%運營商 – Pop

+0

我沒有覆蓋它。這就是問題所在? – user3355146

回答

2

如果不重寫%in%,它將使用目前執行的%in%,你可以在help發現:

"%in%" <- function(x, table) match(x, table, nomatch = 0) > 0 

match功能不指望CAttribute類的對象,這說明你的錯誤。

2

爲了更清楚一點,正如@Pop指出相關函數需要實現。在這種情況下,似乎match是相關的功能。 match需要進行一個通用的,限制派遣相關參數

setGeneric("match", signature=c("x", "table")) 

,然後實施

setMethod("match", c(x="CAttribute", table="CAttribute"), 
    function(x, table, nomatch = NA_integer_, incomparables = NULL) 
{ 
    match(getName(x), getName(table), nomatch=nomatch, 
      incomparables=incomparables) 
}) 

我想,這通常就足夠了,即使用match函數(如%in%)現在會工作。但無論出於何種原因,它似乎必須促進%in%到一個通用的

setGeneric("%in%") 

,並以實施

setMethod("%in%", c("CAttribute", "CAttribute"), 
    function(x, table) 
{ 
    match(x, table, nomatch=0L) > 0L 
}) 

對於它的價值,R具有「集團仿製藥」,因此而不是僅僅實現==運營商也將是適當的實現,例如,?Compare

setMethod("Compare", c(e1="CAttribute", e2="CAttribute"), 
    definition=function(e1, e2) 
{ 
    callGeneric(getName(e1), getName(e2)) 
}) 

它說對所有的比較操作符,inclu丁==,使用getName()進行比較。

有了一個基本的類定義

CAttribute <- setClass("CAttribute", representation(name="character")) 

getName <- function(x) [email protected] 

我們有

CAttribute(name="foo") %in% CAttribute(name=c("foo", "bar")) 
## [1] TRUE 

CAttribute(name="foo") == CAttribute(name=c("foo", "bar")) 
## [1] TRUE FALSE 

注意,含有載體,使矢量操作,使[R高性能合理;定義一個標量類並創建它們的列表,就像在原始問題中一樣,可能是非常低效的。

library(microbenchmark) 
microbenchmark(f0=CAttribute(name=rep("A", 1000)), 
       f1=replicate(1000, CAttribute(name="A")), 
       times=5) 
## Unit: microseconds 
## expr  min   lq  median   uq  max neval 
## f0 298.82 306.435 309.681 311.891 334.687  5 
## f1 264214.85 277728.310 286446.876 300839.340 301080.928  5 

如果一個使用一個列表的-標量,那麼這將是必要的工具,例如,「匹配,CAttribute,列表方法」。