【问题标题】:dispatch a S4 method over the slot of a S4 class在 S4 类的插槽上调度 S4 方法
【发布时间】:2013-05-07 11:03:56
【问题描述】:

我想创建一个 S4 方法“myMethod”,它不仅在函数的第一个参数的类上调度,而且在这个类的一个槽的值上调度。

例如

我的对象:
@slot1="A"
@...

我希望 myMethod(myObject) 为 slot1="A" 和 slot2="B" 返回不同的值。

我可以避免在“myObject”的代码中硬编码“if”吗?

【问题讨论】:

    标签: r methods dispatch s4


    【解决方案1】:

    一个不完全不常见的模式是使用小类来提供多个调度

    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, ...))
    

    然后是处理重新调度的方法

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

    在行动:

    >     My = setClass("My", representation(slot1="Base"))
    >     a = My(slot1=A())
    >     b = My(slot1=B())
    >     do(a)
    [1] "My-A"
    >     do(b)
    [1] "My-B"
    

    【讨论】:

    • 这似乎是在插槽的类上调度,而不是在 OP 中说明的值?
    • 我猜我的假设是槽值来自一组有限的可能值,这些值可以很容易地表示为类层次结构。我想这也暗示了人们想要列举可能的行为这一事实。但你是对的,它本身并没有发送值。
    • 谢谢。有没有比在方法中编写if...else... 代码更优雅的模式来调度槽的值?我正在让一个包与另一个包一起工作,所以我想避免建议上游的更改。
    猜你喜欢
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    相关资源
    最近更新 更多