返回引用类的字段列表

时间:2013-09-10 08:18:09

标签: r reference-class

定义返回任意数量字段的函数的正确方法是什么。

  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 个答案:

答案 0 :(得分:1)

可以为定义的字段查询引用类定义,例如

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

所以也许

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
    }))

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