Hi Edna --
Quoting Edna Bell <edna.bell01 at gmail.com>:
> I have put together a test class and methods
>
>> setClass("foo",representation(x="numeric"))
> [1] "foo"
This creates an *S4* class which HAS A 'slot' x that is of type numeric.
>>
setMethod("plot","foo",function(x,y,...)boxplot(x,...))
> [1] "plot"
>> x <- rnorm(100)
>> class(x) <- "foo"
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
> Thanks,
> Edna Bell
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>