2

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.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Johnny
  • 285
  • 1
  • 7

1 Answers1

3

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!')
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • 1
    Ah I see! So in your example, you've defined an implementation of the generic `foo` for the S3 class `bar`? And you could write more implementations of the generic for other S3 classes too, right? – Johnny Apr 21 '21 at 10:28
  • @Johnny Yes, exactly. – Konrad Rudolph Apr 21 '21 at 10:38