Question

I have a ReferenceClass in R.

How can I add a method "print()" to it, which will print the values of all of the fields in the class?

Was it helpful?

Solution

Perhaps a better implementation is the following

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

The following illustrates use of the Config constructor (no need to invoke 'new') and automatic invocation of 'show'

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

OTHER TIPS

Run the following demo in an R console:

# 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

In addition, typing the following shows the source code for the default "show" function that is included with all ReferenceClasses:

config$show
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top