Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend an R S4 object to have new slots and keep the original object working the same way

Tags:

object

oop

r

s4

I have an S4 object of class "DESeqResults". Essentially, I want to be able to add new information to this object. Ideally, I'd just like to add a few slots to it so I can store things like:

myDESet@new_slot = 5 

I'm starting to think I'll have to make a subclass that inherits "DESeqResults" and while I'm not exactly sure how to do that as of yet in R, I am more concerned about how to keep the data from the original object in tact.

Essentially, a library is making and using this "DESeqResults" class object, and after it is created and has some data, it will be used for a lot of functionality. After I create one of these then, I just want to add some new information to the object. If I make a class that extends this class and has extra slots, how could I transfer all the existing data from the original instance of the class into a new instance of the subclass?

What would be the best way to go about achieving what I'm trying to do here? Is it possible to modify the original class before any objects are instantiated so that when they are created they have the extra slots I need? Or is there some other way to achieve this?

Thanks very much!

like image 595
Adam Price Avatar asked Jan 04 '23 07:01

Adam Price


1 Answers

The usual way to do this is to define a new subclass of the parent class:

setClass(
  "myDESRclass",
  contains="DESeqResults",
  slots=c(new_slot="numeric")
) -> myDESRclass

Then you can use as to convert objects to your class:

## x is some DESeqResults object
x <- as(x,"myDESRclass")
x@new_slot <- 5

In most cases you have to make a call to setAs or similar but because DESeqResults is a superclass the as method is pre-defined by R, and works as intended.

If you don't want to take this approach, there are two alternatives but they are less safe:

1) Use S3 instead of S4. It sounds like you don't "own" the DESeqResults class so that could be difficult, but myDESet$new_slot <- 5 will not be an error.

2) Slots are implemented as attributes, so you can set one with attr(myDESet,"new_slot") <- 5. This modified object will still fail any validity check though, so this can be quite unstable.

like image 73
JDL Avatar answered Jan 13 '23 13:01

JDL