Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R testing for reference classes

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
like image 825
Mark Graph Avatar asked Nov 08 '12 21:11

Mark Graph


1 Answers

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
like image 82
IRTFM Avatar answered Oct 11 '22 14:10

IRTFM