Matrix losing class attribute in R

Consider the following code:

> A <- matrix(1:12, ncol=4)
> colnames(A) <- letters[1:4]
> class(A) <- c("foo", "matrix")

when A is a subset, it loses the label of class foo:

> class(A[1:2,])
[1] "matrix"

The same thing happens with vectors. However, the same does not happen with data.frames:

> B <- as.data.frame(A)
class(B) <- c("foo", "data.frame")
> class(B[1:2,])
[1] "foo"        "data.frame"

And, as a rule, applying common functions to objects preserves the class attribute. Not for matrix / numeric / integer objects. What for? And can this behavior be avoided?

+5
source share
1 answer

data.frames have their own subset method [.data.framethat takes care of the class for you. I'm not sure why the primitive does not preserve the class, but it is pretty straightforward to create your own subset method.

`[.foo` <- function(x, i, j, ...) {
  y <- unclass(x)[i,j,...]
  class(y) <- c("foo",class(y))
  y
}
class(A[1:2,])
# [1] "foo"    "matrix"

EDIT:
, NextMethod .

`[.foo` <- `[.bar` <- function(x, i, j, ...) {
  y <- NextMethod(.Generic)
  class(y) <- .Class
  y
}
+7

All Articles