Skip to content
Prev 60104 / 398502 Next

Testing for S4 objects

Let me suggest a different test, because slotNames was written to work
differently when given a string or a class definition.  With your
definition,

R> x <- "classRepresentation"
R> isS4object(x)
[1] TRUE

which I assume is not what you wanted.  (Given a single string, 
slotNames() tries to look up the class definition of that name.)

How about the following?  The logic is that an S4 object must have an
actual class attribute of length 1 (that rules out basic data types,
where class(x) is a string but there is no actual attribute, and also
rules out some S3 objects).  Then if that's true, try to look up the
class definition.  If it is non-null, seems like an S4 object.

R> isS4object <- function(object)(length(attr(object, "class"))==1 &&
+     !is.null(getClass(class(object))))
R> isS4object(x)
[1] FALSE
R> isS4object(getClass(class(x)))
[1] TRUE

This definition seems to work, at least on the examples I could think
of right away.  Notice though, that some classes, such as "ts", that
have been around for a long while are nevertheless legitimate S4
classes, so:

R> t1 = ts(1:12)
R> isS4object(t1)
[1] TRUE

(this applies to either version of isS4object).

There are a couple of details, more appropriate for the r-devel list. 
Seems  a good candidate for a function to add to R.
On Sat, 27 Nov 2004 17:48:30 -0500, John Fox <jfox at mcmaster.ca> wrote: