Search code examples
rloopsdynamicr-s4

Looping through variables in dynamically created S4 class in R


I'm working with an R program where I've dynamically created an S4 class. I would like to somehow loop through each of the variables in this class to write to a table.

classStructure <<- getColumns(jobClass)
myclass <- setClass("myclass", slots = classStructure)
method <<- setClassMethods()

setClassMethods <- function(){
   setGeneric("myclass",
         def = function(myclassVar, level, outFile){
           standardGeneric("myclassMethod")
         })
   setMethod("myclassMethod", signature = "myclass",
        function(myclassVar, level = classLevel, outFile = logFile){
           # Stuff happens
           # Loop through variables here
           # Write table of class variables to file
   }
}

Is this possible? Thanks for any help given.


Solution

  • If object x has a dynamically generated class and you want to apply someFun to each slot and save the results, you can loop as follows:

    slotApply <- function(x,FUN,...){
      cl <- class(x)
      result <- list()
      for(i in slotNames(cl)){
        result[[i]] <- FUN(slot(x,i),...)
      }
      result
    }
    

    You use this slotApply function in a similar way to the other *apply functions:

    > setClass("simpleClass",slots=c(slot1="integer",slot2="numeric")) -> simpleClass
    > x <- simpleClass(slot1=1:5,slot2=rnorm(10))
    > x
    An object of class "simpleClass"
    Slot "slot1":
    [1] 1 2 3 4 5
    
    Slot "slot2":
     [1]  1.00247979 -1.75796879  0.06510241 -0.53409906  0.85805243 -0.30981176 -1.06817163 -1.45182185  0.09195955  1.17004958
    
    > slotApply(x,sum)
    $slot1
    [1] 15
    
    $slot2
    [1] -1.934229
    
    >