在R中动态创建的S4类中遍历变量 [英] Looping through variables in dynamically created S4 class in R

查看:53
本文介绍了在R中动态创建的S4类中遍历变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个R程序,其中已经动态创建了一个S4类.我想以某种方式遍历此类中的每个变量以写入表.

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.

推荐答案

如果对象x具有动态生成的类,并且您想将someFun应用于每个插槽并保存结果,则可以如下循环:

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
}

您可以以与其他* apply函数类似的方式使用此slotApply函数:

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

> 

这篇关于在R中动态创建的S4类中遍历变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆