Search code examples
rgenericsr-s4equality-operator

Make `==` a generic funciton in R


I would like to make == a generic function.

When I run: setGeneric("=="), the definition does not appear to change:

> `==`
function (e1, e2)  .Primitive("==")
> setGeneric("==")
[1] "=="
> `==`
function (e1, e2)  .Primitive("==")

And when I call setgeneric("`==`"), I get the following error:

> setGeneric("`==`")
Error in setGeneric("`==`") : 
  must supply a function skeleton for ‘`==`’, explicitly or via an existing function

I can define the == function with:

`==` <- function(x,y) 42;

And then I can use setGeneric on it. But then I'd have to put the body of the original == there, which seems clunky.

So is there any way to make == be generic in S4?


Solution

  • Thanks to MrFlick's response:

    It turns out that == is already generic (implement in C). So you don't need to call setGeneric.

    Rather, you can just use setMethod.

    setMethod("==",
              c(e1="Class1",e2="Class2"),
              funciton(e1,e2) { .... })