I did ?"NULL<tab> at the command line and was lead to ?"NULL-class" and the
BasicClasses help page in the methods package.
getClass("NULL"), getClass("character") show that these objects are unrelated,
so a class union is the way to define a class that is the union of these. The
essence of the behavior you would like is
setClassUnion("character_OR_NULL", c("character", "NULL"))
.A = setClass("A", slots = c(x = "character_OR_NULL"))
with
> .A(x = NULL)
An object of class "A"
Slot "x":
NULL
> .A(x = month.abb)
An object of class "A"
Slot "x":
[1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
> .A(x = 1:5)
Error in validObject(.Object) :
invalid class "A" object: invalid object for slot "x" in class "A": got class
"integer", should be or extend class "character_OR_NULL"
I understand there are situations where NULL is desired, perhaps to indicate
'not yet initialized' and distinct from character(0) or NA_character_, but want
to mention those often appropriate alternatives.
With
setClassUnion("maybeNumber", c("numeric", "logical"))
every instance of numeric _is_ a maybeNumber, e.g.,
> is(1, "maybeNumber")
[1] TRUE
> is(1L, "maybeNumber")
[1] TRUE
> is(numeric(), "maybeNumber")
[1] TRUE
> is(NA_integer_, "maybeNumber")
[1] TRUE
which I think is consistent with the use of 'superclass' on the setClassUnion
help page.
Martin Morgan
On 9/23/20, 5:20 PM, "R-devel on behalf of Abby Spurdle"
<[email protected] on behalf of [email protected]> wrote:
As far as I can tell, there's no trivial way to set arbitrary S4 slots to
NULL.
Most of the online examples I can find, use setClassUnion and are
about 10 years old.
Which, in my opinion, is defective.
There's nothing "robust" about making something that should be
trivially simple, really complicated.
Maybe there is a simpler way, and I just haven't worked it out, yet.
But either way, could the documentation for the methods package be improved?
I can find any obvious info on NULL slots:
Introduction
Classes
Classes_Details
setClass
slot
Again, maybe I missed it.
Even setClassUnion, which is what's used in the online examples,
doesn't contain a NULL slot example.
One more thing:
The help file for setClassUnion, uses the term "superclass", incorrectly.
Its examples include the following:
setClassUnion("maybeNumber", c("numeric", "logical"))
If maybeNumber was the superclass of numeric, then every instance of
numeric would also be an instance of maybeNumber...
______________________________________________
[email protected] mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel
______________________________________________
[email protected] mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel