[Rd] Format printing inside a matrix
Jialin Ma
m@r||n- @end|ng |rom gmx@cn
Mon Jul 8 04:13:47 CEST 2019
Hi Abby,
> > It is not desirable if a
> > simple matrix subsetting will remove the class attributes of the object.
>
> I'm assuming by "the object" you are referring to the matrix.
> And by "class attribute"-"s" you are referring to all the attributes.
> This is a completely separate discussion from your original post.
> And I don't see what it has to do with printing matrices with a list type.
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 using 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
More information about the R-devel
mailing list