`print` method for ReferenceClass

我的梦境 提交于 2019-12-19 04:12:59

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/22357534/print-method-for-referenceclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!