0

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?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
ChuckP
  • 161
  • 1
  • 6

1 Answers1

1

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)
}
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • I'm new to r programming so I don't really know the syntax here. How exactly do I dispatch to another plot method(is This case I want to plot as if It's a histogram object) – ChuckP Sep 13 '16 at 13:26
  • @ChuckP By calling it. Or, in the absolutely simplest case, by just making your function equal to that for a histogram (this requires that these objects are really similar though): `plot.NewClass = graphics:::plot.histogram` — note the three colons: `plot.histogram` isn’t exported from `graphics` so you need to convince R to access a hidden object in the namespace. This is done via `:::`. – Konrad Rudolph Sep 13 '16 at 13:30