5

Is there a quick and dirty way to test whether an instance is from a reference class?

The standard R object tests yield the following - but nothing that seems to exclusively mark a reference class.

classy <- setRefClass('classy',
    fields = list(
        count = 'numeric'
    ),
    methods = list(
        initialize = function( data=NULL ) {
            .self$data <<- data
        }
    )
)

instance <- classy$new() # instantiation

isS4(instance) # TRUE
mode(instance) # "S4"
typeof(instance) # "S4"
class(instance) # [1] "classy" attr(,"package") [1] ".GlobalEnv"
dput(instance) # new("classy", .xData = <environment>)
str(instance) # 
# Reference class 'classy' [package ".GlobalEnv"] with 1 fields
#  $ count: num(0) 
#  and 13 methods, of which 1 are possibly relevant:
#    initialize
2
  • 4
    Repeat after me: "I will not call Reference Classes R5" Nov 8, 2012 at 21:37
  • 3
    Repeat after me "r5 is a perfectly valid abbreviation for a long name"
    – hadley
    Nov 9, 2012 at 0:51

1 Answer 1

6

Try this:

 inherits(instance, "envRefClass")
# should return [1] TRUE

This is found in the "Inheritance" section of help(ReferenceClasses). And I suspect that John Chambers might object to calling this "dirty".

Apropos Hadley's comment, is is documented to behave mostly the same as inherits but has the added capacity to recognize conditional inheritance:

is(instance, "envRefClass")
#TRUE
3
  • Thanks - really appreciated - while JC may object to the "dirty" label, you must admit it is different to the other ways in which objects are inspected/tested in R. It all adds to the delightful quirkiness of R.
    – Mark Graph
    Nov 8, 2012 at 22:27
  • 2
    I think using is is slightly more canonical for s4 based classes
    – hadley
    Nov 9, 2012 at 0:52
  • Oh, yeah. The mixture of naming conventions and acceptable data types to grouping arguments are a never ending source of errors on my part. OTOH, I would not be surprised to see an isRefClass function appear at some point.
    – IRTFM
    Nov 9, 2012 at 0:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.