Skip to content
Prev 57166 / 63421 Next

Format printing inside a matrix

On 7/7/19 17:41, Jialin Ma wrote:
Is it? One could argue that a more sensible behavior would be that
things like `[`(..., drop=FALSE), rbind(), cbind(), etc... preserve
the class attribute.

Interestingly t() does that:

   m <- matrix(1:6, nrow=2)
   class(m) <- "foo"

   m
   #      [,1] [,2] [,3]
   # [1,]    1    3    5
   # [2,]    2    4    6
   # attr(,"class")
   # [1] "foo"

   t(m)
   #      [,1] [,2]
   # [1,]    1    2
   # [2,]    3    4
   # [3,]    5    6
   # attr(,"class")
   # [1] "foo"

but not aperm() (which in this case would be expected to be
equivalent to t()):

   aperm(m, 2:1)
   #      [,1] [,2]
   # [1,]    1    2
   # [2,]    3    4
   # [3,]    5    6

Reshaping also preserves the class:

   dim(m) <- c(6, 1)
   m
   #      [,1]
   # [1,]    1
   # [2,]    2
   # [3,]    3
   # [4,]    4
   # [5,]    5
   # [6,]    6
   # attr(,"class")
   # [1] "foo"

So if it makes sense for t() and reshaping, it's not clear why it
wouldn't for [, aperm(), cbind(), etc...?

H.