3

I have:

MyClass <- setRefClass("MyClass" , fields = list(data="numeric"))

Let's initialize an object of MyClass:

OBJ <- MyClass(data=1:4)

... and print it on screen:

OBJ

Reference class object of class "MyClass"
Field "data":
[1] 1 2 3 4

I would like to change the way it gets printed so I wrote this method:

print.MyClass <- function(x) { cat("This is printed representation: ") print(x$data) }

Now this works:

print(OBJ)

This is printed representation: [1] 1 2 3 4

this doesn't:

OBJ

Is there any way to implement my print method with just typing OBJ?

I have tried also show, or (OBJ), but no love for me.

Daniel Krizian
  • 4,586
  • 4
  • 38
  • 75
  • You can add a `show` method to your reference class as detailed in `?setRefClass`. `MyClass$methods(show = function(){print("This is printed representation: "); print(data)})` for example. – jdharrison Mar 12 '14 at 16:28
  • Yes it works as requested when I type `OBJ`. Would you like to make this into a regular answer, which I will readily accept and close. Thanks again @jdharrison – Daniel Krizian Mar 12 '14 at 16:42

1 Answers1

5

You can add a show method to your reference class as detailed in ?setRefClass. As an example

MyClass <- setRefClass("MyClass" , fields = list(data="numeric"))

MyClass$methods(show = function(){print("This is printed representation: ")
                                  print(data)})

OBJ <- MyClass(data=1:4)

> OBJ
[1] "This is printed representation: "
[1] 1 2 3 4
jdharrison
  • 30,085
  • 4
  • 77
  • 89