rr-s3

Difference between 'generic' and 'method'?


I noticed that the following functions in R have two slightly different classifications:

sloop::ftype(t.test)
#> [1] "S3"      "generic"

sloop::ftype(t.data.frame)
#> [1] "S3"     "method"

Created on 2021-04-21 by the reprex package (v1.0.0)

One is a 'generic' and one is a 'method' but I'm struggling to differentiate the two: my understanding of a 'generic' is that it is a method - specifically, a method which acts on an input object according to its class.


Solution

  • A method implements a generic (or, on a more technical level, a method gets called by a generic via UseMethod).

    That is, a generic function calls UseMethod; it might look something like this:

    foo = function (x, ...) UseMethod('foo')
    

    Whereas a method is a function that implements the generic for a specific S3 class; for instance:

    foo.bar = function (x, ...) message('class of x is bar!')