19

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?

t-kalinowski
  • 1,420
  • 11
  • 21
  • 6
    This probably has to do with [`auto-printing`](https://stackoverflow.com/a/34638830/496488) occurring when you type the bare object name for an object class that has an auto-print method defined. A comment in the linked answer implies that you can't change this in R, as it's handled at the C level. If you change your function name to `print.array2` and then do `class(x) = "array2"; x` you'll see that your new `array2` `print` method is called, even when you type the bare object name in the console. But that's not all that helpful unless you're creating a new object class. – eipi10 Feb 19 '18 at 02:30

1 Answers1

1

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.

Thomas Guillerme
  • 1,747
  • 4
  • 16
  • 23