Question

Consider the following code:

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

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

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

The same happens with vectors. Yet, the same doesn't happen with data.frames:

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

And usually, applying generic functions to objects preserves the class attribute. Not for matrix/numeric/integer objects. Why? And can this behavior be avoided?

Was it helpful?

Solution

data.frames have their own subset method [.data.frame, which takes care of the class for you. I'm not sure why the Primitive doesn't preserve the class, but it's pretty straight-forward 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:
As others have mentioned, NextMethod should be used here.

`[.foo` <- `[.bar` <- function(x, i, j, ...) {
  y <- NextMethod(.Generic)
  class(y) <- .Class
  y
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top