Search code examples
rclassinheritancematrixr-s4

Don't print all slots of class instance by default


I wrote class that extends matrix by adding one slot for history of operations done on given matrix.

setClass("newMatrix", representation(history = "character"),  contains = "matrix")

I want instances of this class to act as matrices, so I want only .Data slot to be printed out by default, and history to be called by function.

m <- new("newMatrix", 1:4, 2, 2, history = "ipsum")
> m
An object of class "newMatrix"
     [,1] [,2]
[1,]    1    3
[2,]    2    4
Slot "history":
[1] "ipsum"

Is there a way to make R print by default only .Data slot of this class, like this:

> m
     [,1] [,2]
[1,]    1    3
[2,]    2    4

Solution

  • Given you're in a S4 setting, the best way is to define a show method:

    setClass("newMatrix", representation(history = "character"),  contains = "matrix")
    m <- new("newMatrix", 1:4, 2, 2, history = "ipsum")
    
    setMethod("show",
              "newMatrix",
              function(object){
                show([email protected])
              })
    

    If you need a separate print method, you also need to provide an S4 method for that. The classic construct to avoid S3/S4 conflicts, is the following:

    print.newMatrix <- function(x, ...){
     print([email protected])
    
    }
    
    setMethod("print",
              "newMatrix",
              print.newMatrix)
    

    Constructing a separate print method is not really necessary, as print() will use the show() method here if it can't find a print method for the class newMatrix.

    You could create only the S3 method, but that can get you into trouble as explained on the help page ?Methods_for_S3

    ( see : https://www.rdocumentation.org/packages/methods/versions/3.4.3/topics/Methods_for_S3 )