Write S3 methods for generics from other packages without importing that package?

I am working on a package that provides custom date S3 classes. I want to export methods for lubridate users, such as year.mydate() and month.mydate(), but I do not want lubridate as a dependency of my package (just a "Suggests". Is this at all possible or do I have to give up on that idea?

is this at all possible?

1 Like

The Suggested Packages section of Writing R Extensions gives an example for this kind of thing:

if (requireNamespace("rgl", quietly = TRUE)) {
  rgl::plot3d(...)
} else {
  ## do something else not involving rgl.
}

Here, requireNamespace() effectively checks if a package exists. While it does load the namespace, it doesn't attach it. So it shouldn't affect the rest of your package's code.

Thanks for the Answer, I know about requireNamespace(), but this is not what I am asking about.

I want to provide an S3 method --- let's say year.mydate() for lubridate::year() --- without having to import lubridate::year() from the lubridate NAMESPACE.
One option would be to define my own year() generic, but then I would get conflict warning when the user tries to load my package as well as lubridate, which I also want to avoid.

(For this special case it is enough if I define a as.POSIXlt() method for mydate(), but I was wondering if this is possible in general for S3 classes)

This is an example of dynamic exporting. The hms package does this, as does googledrive I think.

See below for the pillar function that gets exported

See below for how it's dynamically exported when the package is loaded. I've used this myself, pretty useful.

2 Likes

Thanks :slight_smile: i think this is what i was looking for