R: overridden == and% in%

I wrote the s4 class and redefined the "==" operator -

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

If now I want to check if the CAttribute instance is in the CAttributes list,

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

I get the following error

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

What am I doing wrong, how can I check the list of s4 objects for the appearance of a specific object corresponding to the specific operator "=="?

+4
source share
2 answers

If you do not override %in%, it will use the current implementation %in%, which you can find in help :

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

The function matchdoes not expect a class object CAttribute, and this explains your error.

+2
source

, @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))
})

, , ==, getName() .

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

getName <- function(x) x@name

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

- -, , , "match, CAttribute, list-method".

+2

Source: https://habr.com/ru/post/1528927/


All Articles