Avoding s3 method collisions

I have a special s3 class object with class myobj. It has defined methods for select, filter, and collect—e.g. select.myobj, filter.myobj, and collect.myobj. The goal is to have them be methods that feel and look like dplyr.

These methods do not require the use of dplyr so dplyr is not suggested. I want the methods to always be available when the package is imported. The only way that I'm aware of doing this is declaring them as methods like such

select <- function(x, ...) UseMethod("select")

select.myobj <- function(x, ...) { some code here}

When this is done, the methods will collide with dplyr is loaded. The alternative is to suggest dplyr and use vctrs::s3_register(). But then the methods will only be available when dplyr is installed.

Is there a way to get the best of both worlds? Is it possible to conditionally define the generic? For example if dplyr isn't available export the generic?

You can do that if you like. E.g. call find.package() and catch the error and then call registerS3method() to register your method.

Personally I don't love this solution because even if dplyr is not available on the search path now, it might be available in the future, in the same R session.

I think it is better name your generic something else, so the name does not clash with popular packages.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.