Вопрос

I would like to create a S4 method 'myMethod' that dispatches not only on the class of the first argument of the function, but also on the value of one of the slot of this class.

for instance

myObject:
@slot1="A"
@...

I would like myMethod(myObject) to returns something different for slot1="A" and slot2="B".

Can I avoid to hardcode the 'if' in the code of 'myObject'?

Это было полезно?

Решение

A not completely uncommon pattern is to use small classes to provide multiple dispatch

setClass("Base")
A = setClass("A", contains="Base")
B = setClass("B", contains="Base")
My = setClass("My", representation(slot1="Base"))

setGeneric("do", function(x, y, ...) standardGeneric("do"))
setMethod("do", "My", function(x, y, ...) do(x, x@slot1, ...))

and then methods to handle the re-dispatch

setMethod("do", c("My", "A"), function(x, y, ...) "My-A")
setMethod("do", c("My", "B"), function(x, y, ...) "My-B")

In action:

>     My = setClass("My", representation(slot1="Base"))
>     a = My(slot1=A())
>     b = My(slot1=B())
>     do(a)
[1] "My-A"
>     do(b)
[1] "My-B"
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top