Return a list of fields of a Reference Class

旧巷老猫 提交于 2019-12-13 04:22:25

问题


What is the proper way to define a function which returns a arbitrary number of fields.

  A.getFields<-function(values){
  vars<-getRefClass()$fields()
  idx<-names(vars) %in% values
  if(length(fields)<1) 
    return(vars)
  return(vars[idx])
}
A.setFields<-function(...){
  dots <- list(...)
  fieldNames <- names(dots)
  for(i in seq_along(dots))
    assign(fieldNames[[i]], dots[[i]], attr(.self, ".xData"))
}
A<-setRefClass(Class = "A",
               fields = c(var1 = "list",
                          var2="character"),
               methods = list(getFields=A.getFields
                              ,setFields=A.setFields
                              ,initialize=function(...,var1=list(), var2=character()) {
                                obj<-list(...)[[1]]
                                if(is(obj,"list"))
                                  do.call(.self$setFields,obj)
                                else{
                                  .self$var1<-as.list(var1)
                                  .self$var2<-as.character(var2)
                                }
                                .self
                              })
)

a<-A(var1=list(1:3),var2="A")
a$getFields(c("var2"))
a$getFields(c("var2","var1"))

回答1:


The reference class definition can be queried for defined fields, e.g.,

getRefClass("A")$fields()
a = A()
a$getRefClass()$fields()

so maybe

A = setRefClass("A", fields=c(var1="list", var2="character"),
    methods=list(getFields=function(values) {
        flds = names(getRefClass()$fields())
        if (!missing(values))
            flds = flds[flds %in% values]
        result = setNames(vector("list", length(flds)), flds)
        for (fld in flds)
            result[[fld]] = .self[[fld]]
        result
    }))

with

> A(var2=letters[1:5])$getFields("var2")
$var2
[1] "a" "b" "c" "d" "e"


来源:https://stackoverflow.com/questions/18713847/return-a-list-of-fields-of-a-reference-class

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