4

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!

yusuzech
  • 5,896
  • 1
  • 18
  • 33

1 Answers1

5

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"
yusuzech
  • 5,896
  • 1
  • 18
  • 33