Skip to content
Prev 57163 / 63424 Next

Format printing inside a matrix

Hi Abby,
This is what I means:

Suppose my list of S4 objects looks like following:

  myElement <- setClass("myElement", slots = c(x = "integer"))
  myList <- lapply(1:8, function(x) myElement(x = x))
  myArray <- array(myList, c(2,2,2))
  myArray

  # , , 1
  #
  #      [,1] [,2]
  # [1,] ?    ?
  # [2,] ?    ?
  #
  # , , 2
  #
  #      [,1] [,2]
  # [1,] ?    ?
  # [2,] ?    ?

Then I want to wrap the list with a new class and defining a new print
method for it.

  class(myArray) <- "myArray"
  print.myArray <- function(x) {
      print(`dim<-`(sapply(x, function(x) paste0("'", x at x)), dim(x)))
  }
  myArray

  # , , 1
  #
  #      [,1] [,2]
  # [1,] "'1" "'3"
  # [2,] "'2" "'4"
  #
  # , , 2
  #
  #      [,1] [,2]
  # [1,] "'5" "'7"
  # [2,] "'6" "'8"

This works fine but no longer work after we do some simple operations.

  myArray[1:2, 1:2, 2]

  #      [,1] [,2]
  # [1,] ?    ?
  # [2,] ?    ?

In order to make it work naturally, we have to define the subsetting method.

  `[.myArray` <- function(x, i, j, ...) {
      `class<-`(unclass(x)[i, j, ...], class(x))
  }
  myArray[1:2, 1:2, 2]

  #      [,1] [,2]
  # [1,] "'5" "'7"
  # [2,] "'6" "'8"

And there is a bunch of other methods that needs to be defined for this
specific class. This seems too much if I simply want the default list behavior
plus printing method.

Best regards,
Jialin