R | Analyzing methods for generic functions (S3)
When calling a generic function in R [1] such as print
, it can sometimes be useful to know what method is being called; since different methods are coded as separate functions, their behavior can differ greatly depending which method is being used.
Note that this card specifically deals with the S3 paradigm (which is the most commonly used), and not the R6 and S4 paradigms.
Finding the Full Class Set for Objects:
When it comes to dispatching, the class
function is somewhat misleading, because it only shows a single class for any particular object, when in fact, due to inheritance, it's very much possible for objects to belong to multiple classes, all of which can be used for dispatching. To show all the classes of an object, use the sloop::s3_class
function:
> class(.5)
[1] "numeric"
> sloop::s3_class(.5)
[1] "double" "numeric"
Finding the Method:
To find out what method is being used for a function call, use the sloop::s3_dispatch
function:
> sloop::s3_dispatch(print(.5))
print.double
print.numeric
=> print.default
This shows that R's dispatching looked up 2 method names (print.double
and print.numeric
) that could correspond to .5
, couldn't find them, and so settled on print.default
. Note that it went through both class names in attempting to find a matching method.
> sloop::s3_dispatch(print(iris))
=> print.data.frame
* print.default
Here, iris
is a data.frame
, and the dispatcher was able to find the matching print.data.frame
method. print.default
is still displayed because it would have been the fallback if print.data.frame
was not found.
The sloop
[3] package has a number of other similarly useful functions relating to S3 dispatching.
Getting the Code for the Method:
It may also be useful to examine the code for a method to understand its behavior. In that case you can simply enter in the name of the method into the console, the same way as you would a function. For programming purposes, you can also use either sloop::s3_get_method
or the built-in utils::getS3method
functions to use string parameter(s).
# all will output the code of the method
print.data.frame
sloop::s3_get_method("print.data.frame")
utils::getS3method("print", "data.frame")