2

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.

Trincity
  • 149
  • 9
  • 2
    Please include the libraries and reproducible example data, any function definitions, etc. For code debugging please always ask with a [reproducible](https://stackoverflow.com/q/5963269/1422451) example per the [MCVE](https://stackoverflow.com/help/mcve) and [`r`](https://stackoverflow.com/tags/r/info) tag description, with the desired output. – Hack-R Jun 29 '18 at 23:26
  • 1
    Probably with `slotNames("myclass")`. – Alexis Jun 30 '18 at 13:28
  • Here are a few examples of what the classStructure may be: classStructure <- c(name = "character", type = "character", date = "POSIXct") or classStructure <- c(assessment = "character", level = "numeric, id = "numeric", error = "character") – Trincity Jul 09 '18 at 16:21

1 Answers1

2

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

> 
JDL
  • 1,496
  • 10
  • 18
  • Thank you for this, but I'm trying to figure out how to take the class structure and put them into a dataframe format. Would you have any thoughts on that? – Trincity Jul 09 '18 at 16:26
  • Assuming you mean that each slot in the class is meant to be a column of the resulting data frame, you should be able to wrap the call to `slotApply` in a call to `as.data.frame`. If that doesn't work then that means the contents aren't suitable for making into a data frame (they don't all have the same length, for example). It also works in the edge case of a class with no slots at all. – JDL Jul 09 '18 at 18:40