Search code examples
rr-s4r-s3

How to create custom print method for S4 object in R


I created a custom class and print method:

#custom class
myClass <- setClass(Class = "myClass",
                    slots = c(a = "character"),
                    prototype = list(a = character()))
#custom print method
print.myClass <- function(theObject){
    print("2")
}
#create a variable for testing
test <- myClass(a = "1")

It works fine if I use print(test):

> print(test)
[1] "2"

But if I just run the variable itself without print(), it displays differently.

> test
An object of class "myClass"
Slot "a":
[1] "1"

What should I do to make the custom print method works the same way when I run it without using print()?

Thanks!


Solution

  • Just figured it out by myself. For S4 objects, you need to use show().

    It works if I use this:

    setMethod(f = "show",
              signature = "myClass",
              definition = function(object){
                  print("2")
              })
    

    it works:

    > test
    [1] "2"