문제

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