In R, how can I indicate that the general method accepts an argument ... (dots)?

I have a general method in R:

setGeneric(
    "doWork", 
    function(x) { 

        standardGeneric("doWork")
    })

setMethod(
    "doWork", 
    signature = c("character"), 
    definition = function(x) { 

        x
    })

How to add an argument ... (dots) to a definition?

+4
source share
1 answer

Maybe I missed something, but you can do:

setGeneric("doWork", function(x, ...) standardGeneric("doWork"))
setMethod("doWork", signature = c("character"), 
  function(x, ...) do.call(paste, list(x, ..., collapse=" "))
)

Then:

> doWork("hello", "world", letters[1:5])
[1] "hello world a hello world b hello world c hello world d hello world e"
> doWork(1:3, "world", letters[1:5])
Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘doWork’ for signature ‘"integer"

You can even send ..., if you wish, under certain circumstances. From ?dotsMethods:

Starting with version 2.8.0 of R, S4 methods can be sent (selected and called) matching the special argument "...". Currently, "..." cannot be confused with other formal arguments: either the signature of a common function is only "..." or it does not contain "...". (This restriction may be removed in a future version.)

, , , "":

setGeneric("doWork2", function(...) standardGeneric("doWork2"))
setMethod("doWork2", signature = c("character"), 
  definition = function(...) do.call(paste, list(..., collapse=" "))
)
doWork2("a", "b", "c")  # [1] "a b c"
doWork2("a", 1, 2)      # Error
+4

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


All Articles