循环遍历 R 中动态创建的 S4 class 中的变量
Looping through variables in dynamically created S4 class in R
我正在使用一个 R 程序,我在其中动态创建了一个 S4 class。我想以某种方式遍历此 class 中的每个变量以写入 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
}
}
这可能吗?感谢您提供的任何帮助。
如果对象 x
有一个动态生成的 class 并且您想将 someFun
应用到每个槽并保存结果,您可以循环如下:
slotApply <- function(x,FUN,...){
cl <- class(x)
result <- list()
for(i in slotNames(cl)){
result[[i]] <- FUN(slot(x,i),...)
}
result
}
您使用此 slotApply
函数的方式与其他 *apply 函数类似:
> 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 class。我想以某种方式遍历此 class 中的每个变量以写入 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
}
}
这可能吗?感谢您提供的任何帮助。
如果对象 x
有一个动态生成的 class 并且您想将 someFun
应用到每个槽并保存结果,您可以循环如下:
slotApply <- function(x,FUN,...){
cl <- class(x)
result <- list()
for(i in slotNames(cl)){
result[[i]] <- FUN(slot(x,i),...)
}
result
}
您使用此 slotApply
函数的方式与其他 *apply 函数类似:
> 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
>