R 返回引用类的字段列表

R 返回引用类的字段列表,r,reference-class,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(...) fi

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

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

A.getFields可以查询已定义字段的引用类定义,例如

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


许多thx,getFields的以下函数有一般性差异吗<代码>A。getFields@Klaus代码并不像编写的那样工作,但似乎返回的是字段的类型,而不是它们的值you are right
A.getFields
> A(var2=letters[1:5])$getFields("var2")
$var2
[1] "a" "b" "c" "d" "e"