Search code examples
rgenericsoverloadingr-s4arity

S4 classes - overload a method with a variable number of arguments


I would like to have a variable number of arguments in my S4 generic myMethod such that these are both valid:

myMethod(100)
myMethod(100, 200)

Here is my attempt at a definition:

setGeneric(
    "myMethod", 
    function(x) {

        standardGeneric("myMethod")
    })

setMethod(
    "myMethod", 
    signature = c("numeric"), 
    definition = function(x) {

        print("MyMethod on numeric")
    })

setMethod(
    "myMethod", 
    signature = c("numeric", "numeric"), 
    definition = function(x, y) {

        print("MyMethod on numeric, numeric")
    })

However, this gives the error:

Error in matchSignature(signature, fdef) : more elements in the method signature (2) than in the generic signature (1) for function ‘myMethod’


Solution

  • Your generic should support 2 arguments.

    setGeneric(
      "myMethod", 
      function(x, y) {
        standardGeneric("myMethod")
      })
    

    Also the function in your second method should actually support two arguments:

    setMethod(
      "myMethod", 
      signature = c("numeric", "numeric"), 
      definition = function(x, y) {
        print("MyMethod on numeric, numeric")
      })
    

    More generally, if you want to specify arbitrarily many arguments, you should have a look at the elipsis argument ....