When I read a book named 《Introduction to Scientific Programming and Simulation Using R》, I was confused by the usage of "print" and "show". It said if you use function "show" in your code, then when you call "source" to carry out the code again, the function "show" will not work. Instead, if you use "print" in your code, then it works fine when you "source" it.
I try to find the reason why it is, but only to find most people focus more about the difference between the "cat" and "show", so could anyone tell me the difference between "show" and "print" and in practice, when should I use show and when should use the other?
31 Answer
In R, there are two object oriented programming frameworks: the simple, but not formalized S3 framework, and the complex, but formalized S4 framework. In both frameworks, if you call a generic function such as print
, the actual work is done by another function, specifically crafted for the type of object you are trying to print. For example, if you call print(df)
, and df
is a data.frame, the actual printing will be done by the function print.data.frame
. This is called method dispatching. If not specific method is found, then print.default
is used.
Basically, you can understand show
as the generalization of print
for S4 classes. show
takes a look at an object, and if it is an S4 class object, it calls the respective S4 method defined by the object signature. If it is an S3 object, it dispatches to the relevant print
method.
It is true that show
usually does not return a value, but whether show
or print
returns a value or not depends on the particular function that gets called. The base::print...
methods all return the object invisibly, and the show
methods return invisibly a NULL, but it is a convention rather than a requirement.
ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJoa3BtaWiDdX6OoqVmql2staLAjKKqZqyYmnqltcWfnKudnpiybq7Era6enZ5iwamxjJ%2Bsp5uknryvvNGipa1lkaOxbr%2FHqK4%3D