Search code examples
rinheritanceenvironmentr-s4

Why is S4 inheritance lost between environments?


Suppose I have a class MyClass defined as follows:

setClass(
    "MyClass", 
    slots = c(message = "character"), 
    validity = function(object) { T })

If I create an instance of it, inherits works as expected:

myInstance <- new("MyClass", message = "Hello")

inherits(myInstance, "MyClass")

TRUE

However, it doesn't work after I put the instance into an environment and bring it back again:

e <- new.env(hash = T, parent = emptyenv())

assign("MyInstance", myInstance, envir = e)

inherits(mget("MyInstance", envir = e), "MyClass")

FALSE

But the data is still there:

mget("MyInstance", envir = e)

$MyInstance An object of class "MyClass" Slot "message": [1] "Hello"

How can I tell R to maintain my S4 classes even when saving and loading instances between environments?


Solution

  • mget returns a named list of the objects requested. You're actually examining the list. To examine the object you need to extract it from the output of mget. Alternatively just use get which returns just the object of interest.

    mget is useful when requesting a bunch of objects but if you just want one then get is just fine.