New to S3 methods - can I make a function from another package into a method?

Hi all.
Coding R a long time but have not delved into methods before, but now I have a reason to. However, I am confused about something - in short - can I make a function from another package into an S3 method, or is this a no-no?

Let's say package ABC has a function def() that is just a normal exported function -> so not an S3 or S4 or S7 method in anyway, but it operates on a class from package ABC - lets call that ABCclass Now I write a new package in which I define a class NEWclass and I write my own function called def(). I wanted to used S3 methods to disambiguate/dispatch to something like this:

def <- function (x, ...) {
   UseMethod("def ", x)
 }

def.ABCclass  <-  function(x, ...)  ABC::def() # so is this line allowed/good practice?
def.NEWclass  <-  function(x, ...) sapply(x, dootherstuffs, ...)

I couldn't find any examples like this in the various intro to S3 classes webpages, so I thought it best to check if this is allowed/good practice or not? Thanks.

1 Like

Hi @ghtye ,

it is allowed and it will work until the package maintainer of the ABC package decides to make a s3 class too for the def method. Then basically depending on which package was loaded last R will make the decision of calling that def method. You can read a detailed account here 13 S3 | Advanced R.

So if your package is loaded last it will call your implementation.

Since the maintainer of every R package is listed in the DESCRIPTION file - reach out and ask if there are any plans to change the function in the future.

2 Likes

I 100% agree this is a good idea. If your package is that closely related to an existing one, it would be best to coordinate some.

Warning that managing S3 methods between packages can get complex quick. Is your hypothetical functiondef have a generic defined in base R, eg summary(), plot(), etc? If yes, different packages can define new methods for their own classes without any issue. However, if the S3 generic is not defined in a different package, then the two packages will continue to conflict based on the load order (because the S3 generic defined in whichever package is loaded second overwrites the previous one).

1 Like

Thanks both for very helpful answers and for making clear the possible pitfalls. I will consider you thoughts and advice!

1 Like