Search code examples
stanrstan

How to inherit stan's S4 class


I develop some package using rstan::stan(). I make a function whose return value is an S4 class object generated by rstan::stan(). To access estimates comfortablely or to add an information for data, I want to make a new S4 class object which inherits S4 class of rstan::stan()so that there is new slots.

Furthermore, the new S4class object also can be available for any functions in rstan such as rstan::traceplot().


fit  <-  rstan::stan( model_name=scr, data=data) # This is a fictitious code.

Suppose we get S4 (stanfit) object named fit .

Define an extended class of stanfit

InheritedClass  <- setClass("InheritedClass",

             # New slots
               representation(slotA="character",
                              slotB="character",
                              slotC="numeric"),


               contains = "stanfit"
)

To create an S4 object of the inherited class using an existing S4 class object ,i.e., fit, so what I need is only to input values for added new slots, i.e., slotA, slotB, slotC.

Using the following code, we can convert the S4 object for old class to inherited class:

fit2 <- as(fit,"InheritedClass")

Using this we can edit slot like following:

   fit2@slotA <- "aaaaaaaaaaaa"

Solution

  • See help(setClass). I believe it would be something like

    setClass("classname", slots = c(foo = "numeric", bar = "character"),
             contains = "stanfit")
    

    And I'm sure you would have to include rstan in the Imports: line of the DESCRIPTION file in your package in order for it to find the S4 class definition for stanfit.