Search code examples
rr-s3

How to treat an object of a class same as another for a generic


I have classified an object to NewClass, how can I use a function, say plot, on the object as if It's of a known class, say hist?


Solution

  • Simple: just provide the required method:

    plot.NewClass = function(x, y, ...) { … }
    

    In the easiest case you can just dispatch to another plot method in the implementation.

    If your NewClass object is actually a histogram object in disguise, you can use the following trick:

    plot.NewClass = function (x) {
        # “unmask” histogram object
        class(x) = 'histogram'
        plot(x)
    }