Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matrix losing class attribute in R

Tags:

oop

r

r-s3

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?

like image 415
gappy Avatar asked Sep 23 '11 17:09

gappy


1 Answers

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
}
like image 121
Joshua Ulrich Avatar answered Sep 20 '22 03:09

Joshua Ulrich