1

I have defined the following in R:

plotWaterfall         <- function(x, ...) UseMethod("plotWaterfall")
plotWaterfall.default <- function(x, ...) {print("Default method does nothing")}
plotWaterfall.vector  <- function(x, ...) {print("Vector method does something")}

Now if I test the following example:

x<-c(1,2,3)
plotWaterfall(x)

it will print "Default method does nothing" indicating that the S3 framework matches the default method instead of the vector method. Now why is that?

Dr. Mike
  • 2,451
  • 4
  • 24
  • 36

1 Answers1

2

It's because the class of your vector is numeric. So you have to do this:

plotWaterfall.numeric  <- function(x, ...) {print("Numeric vector")}

plotWaterfall(x)
[1] "Numeric vector"

You can determine the class of an object with the class() function:

class(x)
[1] "numeric"

This behaviour is described in the help for ?UseMethod:

Method dispatch takes place based on the class(es) of the first argument to the generic function or of the object supplied as an argument to UseMethod

Andrie
  • 176,377
  • 47
  • 447
  • 496
  • Thank you for you answer. The only thing that confuses me a bit then is the internal working of is.numeric and is.vector since > is.vector(a) [1] TRUE > is.numeric(a) [1] TRUE Does that mean that vector is not a "class" in the sense as data.frame is a "class"? – Dr. Mike Dec 07 '12 at 10:17
  • Indeed, like you say, it's pretty obvious from the documentation. Thank you again. – Dr. Mike Dec 07 '12 at 10:22
  • 1
    @Dr.Mike the `is.*` functions are somewhat orthogonal to the S3 class system. It's confusing – hadley Dec 07 '12 at 14:22