Looping through variables in dynamically created S4 class in R

拜拜、爱过 提交于 2019-12-12 19:19:38

问题


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.


回答1:


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

> 


来源:https://stackoverflow.com/questions/51110439/looping-through-variables-in-dynamically-created-s4-class-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!