r - 在R中动态创建的S4类中循环变量
问题描述
我正在使用一个 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
}
}
这可能吗?感谢您提供的任何帮助。
解决方案
如果 objectx
有一个动态生成的类,并且你想应用someFun
到每个 slot 并保存结果,你可以循环如下:
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
>
推荐阅读
- node.js - 托管 onCloud Function 的节点 API 给出了非描述性的“finished with status: 'crash'”错误。我的配置正确吗?
- mongodb - 如何使用嵌套数据设计大型 nosql?
- spring - Spring @Bean(name ="name") 与 @Bean @Qualifier("name")
- google-apps-script - 我可以在已发布插件的 onOpen(e) 中使用 getActiveUserLocale() 吗?
- node.js - 无法在 Node.js 应用程序中使用猫鼬对 MongoDB 数据库进行排序
- pyspark - 使用 countDistinct 倾斜数据
- django - 时区是 UTC 实际上是在 settings.py 文件中更改它
- angular - 使用 aot Angular 9 时出现的错误问题
- javascript - 为什么我得到 ESLint - 组件应该写成纯函数?
- php - 值作为空值插入数据库