uh oh, this is creating an *S3* class that IS A numeric that has been
given the class name "foo". The S3 class 'foo' and S4 class 'foo' are
different. Note that you can make anything an S3 class
z=letters
class(z) <- "foo"
because S3 does not have any definition for what a 'foo' class is.
plot(x)
this 'works' but in my view should not -- the method is defined for
the S4 class, not for the S3 class.
y <- new("foo",x=rnorm(50))
Here you're creating an instance of the S4 class. S4 insists that
objects constructed as class 'foo' conform to the class specification
new("foo", x=letters)
Error in validObject(.Object) :
invalid class "foo" object: invalid object for slot "x" in class
"foo": got cl
ass "character", should be or extend class "numeric"
class(y)
[1] "foo"
My question is: should I have a "foo" function which sets the class
to "foo", please? or a sort of Validity checker, please?
I think normally one would have class "Foo" (capitalized; this is my
style & convention, others are free to do as they please) with
constructor
setClass("Foo", representation=representation(x="numeric"))
Foo <- function(x=numeric(), ...)
{
new("Foo", x=x, ...)
}
I'd normally also define a validity method with setValidity("Foo",
<etc>) if my class had constraints other than 'slot x has to be
numeric' (which is checked by the default validity method). Dispatch
on validity methods is different from on standard methods, as
explained in ?setValidity.
Hope that helps,
Martin