Thursday, 3 October 2013

Why can a matrix 'protect' itself and how can I implement real restrictions to custom classes?

Why can a matrix 'protect' itself and how can I implement real
restrictions to custom classes?

I have been trying to get my ahead around validity of objects. I have read
Hadley's advanced programming and get what he says about he says about
aiming at your feet (with a gun):
"R doesn't protect you from yourself: you can easily shoot yourself in the
foot, but if
you don't aim the gun at your foot and pull the trigger, you won't have a
problem"
So this holds for S3. Looking for a more rigorous implementation I looked
into S4. The man page to setValidity brought up the following:
setClass("track",
representation(x="numeric", y = "numeric"))
t1 <- new("track", x=1:10, y=sort(stats::rnorm(10)))
## A valid "track" object has the same number of x, y values
validTrackObject <- function(object) {
if(length(object@x) == length(object@y)) TRUE
else paste("Unequal x,y lengths: ", length(object@x), ", ",
length(object@y), sep="")
}
## assign the function as the validity method for the class
setValidity("track", validTrackObject)
## t1 should be a valid "track" object
validObject(t1)
## Now we do something bad
t2 <- t1
t2@x <- 1:20
## This should generate an error
## Not run: try(validObject(t2))
Bottom line: If I do not add validObject to the initializer or constructor
there's little I can do. Also this post from Martin Morgan and
bioconductor's Seth Falcon was interesting, still though I could always
t2@x <- 1:1111.
I guess there's not much I can do about this? Though the matrix class for
example makes me wonder if there's an option.
a <- matrix(c(1:12),3,4)
cbind(a,"somechar")
# or similarily
a[1,1] <- "b"
Obviously all elements of a matrix have to be of the same class. So that's
why once a character is added all elements are coerced to the common
denominator, which is class character.
So my question is: How is this possible? In which way is the matrix class
defined, that it can protect the restriction "some class for all elements"
by any means? And is there a way to implement such a restriction to a
custom class, too?
E.g.: class of class 'customlist' that has to be a named list and names
being restricted to only be two chars long.

No comments:

Post a Comment