Skip to content
Prev 59878 / 398502 Next

Testing for S4 objects

JohnF> Dear r-help list members, Is there a way to test
    JohnF> whether an object is an S4 object? The best that I've
    JohnF> been able to come up with is

    JohnF> 	isS4object <- function(object) !(is.null(slotNames(object)))

you can drop one pair of "(..)" to give

  isS4object <- function(object) !is.null(slotNames(object))


    JohnF> which assumes that an S4 object has at least one
    JohnF> slot. I think this is safe, but perhaps I'm missing
    JohnF> something.

The question is a very good one -- that I have posed to R-core a
while ago myself.

Inside  utils:::str.default  {which doesn't show the many
commments in the *source* of str.default()}, I have wanted a way
that even works when the 'methods' package is not attached and
use the more obscure 

    #NOT yet:if(has.class <- !is.null(cl <- class(object)))
    if(has.class <- !is.null(cl <- attr(object, "class")))# S3 or S4 class
	S4 <- !is.null(attr(cl, "package"))## <<<'kludge' FIXME!
	##or length(methods::getSlots(cl)) > 0

For the time being, I'd keep your function, but I don't think
we'd guarantee that it will remain the appropriate test in all
future.  But till then many things will have happened (if not
all of them ;-).

Martin Maechler, ETH Zurich