问题
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