jackb
jackb

Reputation: 704

Overloading of %in% operator in R

I've problems in overloading the %in% operator in R. After overloading the == operator too because my "Type" class is not a basic value in R and %in%:

setMethod("==", signature(e1 = "Type", e2 = "ANY"), function (e1, e2) {
    class(e2)=="Type" && e1$name == e2$name
})  
setMethod("==", signature(e1 = "ANY", e2 = "Type"), function (e1, e2) {
    class(e1)=="Type" && e1$name == e2$name
})  

setMethod("%in%", signature(e1 = "Type", e2 = "list"), function (e1, e2) {
    for (i in e2) {
        if (e1 == i)
            return(TRUE);
    }
    return(FALSE);
})

The last method returns the following error

Creating a generic function from function ‘%in%’ in the global environment
Errore in match.call(definition, call, expand.dots) : 
    unused arguments (e1 = c("Type", ""), e2 = c("list", ""))

How could I solve my problem? Thanks in advance

Upvotes: 2

Views: 274

Answers (2)

Max Candocia
Max Candocia

Reputation: 4385

I find that the easiest way to overload operators is to do a function similar to the following:

"%in%" = function(x,y) {
    if(parameter_condition) {
        response_function
    } else {
    .Primitive("%in%")(x,y)
    }
}

Upvotes: 1

BrodieG
BrodieG

Reputation: 52637

You have the wrong arguments. Look at:

`%in%`
function (x, table) 
match(x, table, nomatch = 0L) > 0L
<bytecode: 0x7ffd5984e978>
<environment: namespace:base>

You need to change your method to have x and table as the arguments. That's why you get the error unused arguments (e1 = c("Type", ""), e2 = c("list", "")), because e1 and e2 aren't part of the generic definition.

Upvotes: 3

Related Questions