1

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!

nicola
  • 24,005
  • 3
  • 35
  • 56
chl111
  • 468
  • 3
  • 14

1 Answers1

2

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 
#--------
nicola
  • 24,005
  • 3
  • 35
  • 56