Search code examples
rprintfr-s4reference-class

Customize the console printing for S4/RC objects in R


In R we can simply type the variable name in the console, the console will automatically print out the value. I have created a new S4/RC class define, and would like to create a nicer way to automatically "print" in the console. How do I edit the console printing functions for a new class?

Here is my code in the console:

ClassA<-setRefClass("ClassA",fields=list(value="numeric"))

"print.ClassA"<-function(object){
      cat("--------\n")
     cat(object$value,"\n")
     cat("--------\n")
}

classobject<-ClassA$new(value=100)

classobject # it doesn't print nicely in the console.
#Reference class object of class "ClassA"
#Field "value":
#[1] 100

print(classobject) # this works
#--------
#100 
#--------

My goal is to avoid typing "print" all the time; just type the object name in the console, it will print out nicely, just like calling print().

Thanks!


Solution

  • You need to define a show method for your RefClass object. Read ?setRefClass for details regarding how to write methods. This works:

    #the print function: note the .self to reference the object
    s<-function(){
         cat("--------\n")
         cat(.self$value,"\n")
         cat("--------\n")
    }
    #the class definition
    ClassA<-setRefClass("ClassA",fields=list(value="numeric"),methods=list(show=s))
    classobject<-ClassA$new(value=100)
    classobject
    #--------
    #100 
    #--------