Search code examples
rr-s4

Create conversion methods between S4 classes from other packages


Suppose I want to create an R package which defines coercion methods (methods::as) between S4 classes which are defined in other packages.

When I'm creating a package with its own S4 class, I can add conversions to and from other classes like this:

setAs("MyClass", "OtherClass", function(from) myfun(from))

And these work fine once the package is loaded, provided that the classes are exported correctly.

But now suppose that I want to take class A from packageA, and class B from packageB, both of which are S4 classes, and I want to create my own conversion functions to/from A<->B (assuming that neither package defined a conversion function to/from the class of the other package).

If I try to add something like this:

setAs("A", "B", function(from) castAtoB(from))
setAs("B", "A", function(from) castBtoA(from))

And then install and load the package, the methods won't be available - e.g. something like this:

library(methods)
library(packageA)
library(packageB)
library(myPackage)

objA <- packageA::createObjA()
as(objA, "B")

Will fail with a message like:

Error in as(objA, "B") : 
  no method or default for coercing “A” to “B”

How can I register these methods so that they would be available when loading my package?


Solution

  • I'll answer myself: getting this to work requires adding the following line in the DESCRIPTION file:

    export()
    

    Then it works correctly.