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:
printis the generic.print.aovoverridesprintfor the S3 classaov.
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)
- go over all available generics using
.knownS3Generics. - Get their methods with
methods() - 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.