I would like to define a different print method for arrays, but I’m afraid I’m not understanding something about S3 dispach. My custom print method is called if I call print(x) explicitly, but is not called if I just type x at the console. However, if I define a custom S3 class, then the appropriate print method is called.
A similar thing happens if I try to define a method for print.numeric
Here is a minimal example:
print.array <- function(x, ...) cat("Hi!\n")
x <- array(1:8, c(2,2,2) )
print(x) # the print method defined above is called
# Hi!
x # the print method defined above is NOT called
Does anyone have any insights into what is happening? What function is actually doing the printing when just x is evaluated at the console?
You need to define the S3 method in a NAMESPACE (see here) in an extension structure (package) as follows:
export(print.array)
S3method(print, array)
I suggest you use devtools to create your "package" (that can easily contain only your print.array function), you'll find some excellent resources here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With