1

How to use/maintain my S4 class with same name as S4 class in another R package?

I'm writing a large R package that includes an S4 class named 'FeatureSet'. Unfortunately, this is also the name of a virtual S4 class in the widely used 'oligo' package. When I load my package first, and then oligo, and call

new("FeatureSet")

I get the error

Error in new("FeatureSet") :
  trying to generate an object from a virtual class ("FeatureSet")

In the NAMESPACE file, I've tried including 'exportClasses' and 'exportClassPattern' to export this S4 definition, or all S4 definitions, from my package without luck. I've also included

exportMethods(coerce, initialize, show)

as I've defined methods for these generics in my package.

Is there a best-practice way to write R code to recognize only a specific S4 definition when multiple definitions with the same name are attached? I could, of course, give my class a different name, but there must be some way to make sure that my classes don't collide with those in some other package in the future. I've spent quite a while looking through the usual forums and documentation and was surprised to see that this question was not answered anywhere. Thanks in advance!

Adam Gower
  • 11
  • 1

1 Answers1

2

I think the best practice is to choose a different, more descriptive name. It is inherently confusing to have two objects of the same name but different structure.

You can construct an instance of 'your' class via

new(getClass("FeatureSet", where=getNamespace("YourPackage")))`

probably wrapped in a simple 'constructor' function.

While in principle the methods package 'knows' the difference between an instance of your class and a class of the same name from another package, you are almost certainly going to run into implementation bugs that will frustrate you and your users.

Martin Morgan
  • 45,935
  • 7
  • 84
  • 112
  • Thanks very much, @Martin-Morgan! I had started playing around with something similar to what you described above, though I was trying to use `envir=as.environment("MyPackage")` instead of `where=getNameSpace("MyPackage")` (without any luck!) I've decided to go ahead and add a prefix to all of the S4 class names in my package (many of which have fairly generic-sounding names like FeatureSet), which should prevent any future conflicts. – Adam Gower Sep 01 '16 at 01:02
  • Isn't this saying all packages should share a common global namespace for classes? Isn't the whole point of namespaces to make this kind of thing simple wtih aPackage:: type prefixes? A more theoretical version of this is asked here: https://stackoverflow.com/questions/60726607/r-s4-classes-with-the-same-name-from-different-packages – Stuart R. Jefferys Mar 19 '21 at 22:54
  • Might be worth making sure your concerns are addressed at https://github.com/RConsortium/OOP-WG – Martin Morgan Mar 22 '21 at 08:46