0
> plot
function (x, y, ...) 
UseMethod("plot")
<bytecode: 0x000000000826f240>
<environment: namespace:graphics>

If you type in plot, you get the above. Note that the function takes two parameters.

Now I have a class, A, and I'd like to give it its own plot-method. So I can write

plot.A <- function(object)

but note that I only want a plot-function that takes 1 argument (and not x, y).

So what do I do?

Janus
  • 165
  • 4
  • `plot.A <- function(x, ...) {}`. Just like `graphics:::plot.data.frame` – Gregor Thomas Sep 24 '19 at 17:44
  • But I was told that methods must take the same parameters as the generic function? So since generic.plot takes x, y, our method plot.a must also take x, y? – Janus Sep 24 '19 at 17:45
  • 1
    I think `plot.data.frame` is a pretty good counter-example. The `...` gives some flexibility, I guess. – Gregor Thomas Sep 24 '19 at 17:47
  • So what exactly are you trying to do that you cannot get to work? It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Sep 24 '19 at 18:04

1 Answers1

0

Are you trying to do something like this? Basically you need to just make the plot.A() function to be whatever you need it to be. I find the following resource helpful.

http://adv-r.had.co.nz/OO-essentials.html

A <- function(x) {
  if (!is.data.frame(x)) stop("X must be a data.frame")
  structure(list(x), class = "A")
}

plot.A <- function(x, ...) {
  plot(x[[1]]$mpg, x[[1]]$cyl, ...)
}

a <- A(mtcars)

plot(a)