Skip to content
Prev 389823 / 398503 Next

Dispatching on 2 arguments?

If you want to use the 'methods' package, you could do something like:


replace <- function (p1, p2, ...)
{
    stop(gettextf("cannot 'replace' with arguments of class %s and %s",
        sQuote(class(p1)[1L]), sQuote(class(p2)[1L])))
}


methods::setGeneric("replace")


methods::setMethod("replace", signature = c(p1 = "pm", p2 = "numeric"),
definition = replace.pm.numeric)
methods::setMethod("replace", signature = c(p1 = "pm", p2 = "character"),
definition = replace.pm.character)


First, we make the default function. I'm not sure what you want that to
look like, but I've made an example above.
Second, you make it generic so that you can provide methods for it.
Last, you add the methods you want. You specify the name of the generic
function, "replace", the classes of arguments it will accept, and then its
function definition.
You can use ?methods::setGeneric and ?methods::setMethod for help with
either of these functions. I hope this helps!

On Sun, Nov 7, 2021 at 1:55 AM Leonard Mada via R-help <r-help at r-project.org>
wrote: