我正在使用R程序,其中已动态创建了S4类。我想以某种方式遍历此类中的每个变量以写入表。
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
}
}
这可能吗?感谢您的帮助。
答案 0 :(得分:2)
如果对象x
具有动态生成的类,并且您想将someFun
应用于每个插槽并保存结果,则可以如下循环:
slotApply <- function(x,FUN,...){
cl <- class(x)
result <- list()
for(i in slotNames(cl)){
result[[i]] <- FUN(slot(x,i),...)
}
result
}
您可以像其他* apply函数一样使用此slotApply
函数:
> 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
>