在R中,如何在ReferenceClass中打印字段的值?

时间:2014-05-04 15:00:15

标签: r reference-class

我在R中有一个ReferenceClass。

如何向其添加“print()”方法,该方法将打印类中所有字段的值?

2 个答案:

答案 0 :(得分:3)

或许更好的实现是以下

Config = setRefClass("Config",
  fields = list(    
    ConfigBool = "logical", 
    ConfigString = "character"),
  methods = list(
    ## Allow ... and callSuper for proper initialization by subclasses
    initialize = function(...) {
        callSuper(..., ConfigBool=TRUE, ConfigString="A configuration string")
        ## alterantive:
        ##    callSuper(...)
        ##    initFields(ConfigBool=TRUE, ConfigString="A configuration string")
    },
    ## Implement 'show' method for automatic display
    show = function() {
        flds <- getRefClass()$fields()
        cat("* Fields\n")
        for (fld in names(flds))  # iterate over flds, rather than index of flds
            cat('  ', fld,': ', .self[[fld]], '\n', sep="")
    })
  )

以下说明使用Config构造函数(无需调用&#39; new&#39;)并自动调用&#39; show&#39;

> Config()
* Fields
  ConfigBool: TRUE
  ConfigString: A configuration string

答案 1 :(得分:2)

在R控制台中运行以下演示:

# Reference Class to store configuration

Config <- setRefClass("Config",
  fields = list(    
    ConfigBool = "logical", 
    ConfigString = "character"
    ),
    methods = list(
        # Constructor.
        initialize = function(x) {
            ConfigBool <<- TRUE
            ConfigString <<- "A configuration string"
        },
        # Print the values of all of the fields used in this class.
        print = function(values) {
            cat("* Fields\n")
            fieldList <- names(.refClassDef@fieldClasses)           
            for(fi in fieldList)
            {
                variableName = fi
                variableValue = field(fi)
                cat('  ',variableName,': ',variableValue,'\n',sep="")           
            }
        }
  )
)

config <- Config$new()
config
config$print()

---test code---

# Demos how to print the fields of the class using built-in default "show()" function.
> config$show()
Reference class object of class "Config"
Field "ConfigBool":
[1] TRUE
Field "ConfigString":
[1] "A configuration string"

# Omitting the "show()" function has the same result, as show() is called by default.
> config
Reference class object of class "Config"
Field "ConfigBool":
[1] TRUE
Field "ConfigString":
[1] "A configuration string"

# Demos how to print the fields of the class using our own custom "print" function.
> config$print()
* Fields
  ConfigBool: TRUE
  ConfigString: A configuration string

此外,输入以下内容会显示默认值&#34; show&#34;的源代码。所有ReferenceClasses附带的函数:

config$show