R: How to determine if a function is an S3 method overriding a generic

Viewed 50

I want to determine if an arbitrary function is an S3 method overriding a generic function. If so, I would want to identify the generic as next step.

The Problem

I need something like HasGeneric(AMethod) that tells me whether my argument AMethod is a method overriding some generic. Or even better FindGeneric(AMethod) that returns the according generic for AMethod.

The first idea I had was parsing the function name because the pattern "generic.class" is recommended to be used to name methods. Example:

  • print is the generic.
  • print.aov overrides print for the S3 class aov.

But string parsing is not without ambiguities: all.equal.data.frame (in the dplyr package).

Furthermore, the pattern isn't even mandatory anymore. Look at this:

a <- 1:5
class(a) <- "SomeTestClassOfMineNotToBeConfused"

# Register some arbitrarily named method as override for print
thisismyaprinter <- function(x) cat("I am A okay")
.S3method("print", "SomeTestClassOfMineNotToBeConfused", thisismyaprinter) # register as override for `print`

methods(class = "SomeTestClassOfMineNotToBeConfused") # now `print` is in the list of methods
#> [1] coerce      initialize  print       show        slotsFromS3
#> see '?methods' for accessing help and source code

print(a) # test works, too
#> I am A okay

As we all know, the output of a as simple vector 1:5 would be:

print(a <- 1:5)
#> [1] 1 2 3 4 5

Tried solutions

All functions that I found to investigate methods either assume that I know the name of the generic or the class (which I don't). I could (of course)

  1. go over all available generics using .knownS3Generics.
  2. Get their methods with methods()
  3. And search them with the function name that I have.

That would not only be slow. It would not even work. When I looked up the methods for print in my example above I got this:

methods(print)
#> [201] ...
#> [202] print.SomeTestClassOfMineNotToBeConfused*           
#> [203] ...

R did register the method with the "generic.class" name pattern. But it is not possible to access this:

print.SomeTestClassOfMineNotToBeConfused(a)
#> Error in print.SomeTestClassOfMineNotToBeConfused(a): konnte Funktion "print.SomeTestClassOfMineNotToBeConfused" nicht finden

... which means R could not find the function print.SomeTestClassOfMineNotToBeConfused.

1 Answers

You can use getDispatchMethodS3 form R.methodsS3

R.methodsS3::getDispatchMethodS3("print" ,
            "SomeTestClassOfMineNotToBeConfused")(a)

#> I am A okay
Related