Search code examples
rr-s4

setMethod for two different object signature in R


How to make it using one setMethod as the function section is the same in the following two line codes? like signature("Triangle|Square"). Thank you.

setMethod("sides", signature("Triangle"), function(object) 3)
setMethod("sides", signature("Square"), function(object) 3)

Solution

  • The usual approach is

    .sides_body = function(object) 3
    setMethod("sides", "Triangle", .sides_body)
    setMethod("sides", "Square", .sides_body)
    

    unless there is a class relationship and the definition is the same across classes

    setClass("Shape")
    setClass("Triangle", contains="Shape")
    setClass("Square", contains="Shape")
    setClass("Circle", contains="Shape")
    setMethod("sides", "Shape", function(boject) 3)
    setMethod("sides", "Circle", function(object) Inf)