Question

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.

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top