初始化任意数量的字段

时间:2013-09-20 14:27:26

标签: r reference-class

函数initFields不是初始化引用类的任意字段的好方法吗?如果不是你会建议什么?我怎么能处理“ANY”类型的字段,因为对于字符串“ANY”我不能像do.call(fields[[i]],list())那样进行调用

Part.initFields<-function(args){
  argNames <- names(args)
  fields<-.self$getRefClass()$fields()
  fieldNames <- names(fields)
  for(i in seq_along(fields)){
     var <- if(is.null(args[[fieldNames[i]]])) do.call(fields[[i]],list())
            else do.call(paste("as.",fields[[i]],sep=""),list(args[[fieldNames[i]]]))
     assign(fieldNames[[i]], var, attr(.self, ".xData"))
   }
 }

Part.initialize<-function(...){
  args<-list(...)
  .self$initFields(args)
  .self
}

Part<-setRefClass(Class = "Part"
                 ,fields = c(var1 = "numeric", var2 = "character")
                 ,methods = list(initialize=Part.initialize
                                ,initFields=Part.initFields))

part<-Part$new(var1=1)

1 个答案:

答案 0 :(得分:2)

使用initialize方法强制参数。明确排除 你不愿意执行的强制。强制使用as(x, "class")而不是尝试从字符串构造函数名称。不要重新实施 initFields

Part <- setRefClass(Class = "Part",
    fields=c(var0 = "ANY", var1 = "numeric", var2 = "character"),
    methods=list(
      initialize=function(...) {
          args <- list(...)
          map <- .self$getRefClass()$fields(); map <- map[map != "ANY"]
          idx <- names(args) %in% names(map)
          args[idx] <- Map(as, args[idx], map[names(args)[idx]])
          do.call(.self$initFields, args)
      }))

简单的测试用例

Part()
Part(var2=1:3)