Search code examples
roopr6

How to check if instance of `R6` class is present in a vector of class instances


I am looking for a way to check if a given instance of R6 class is present in a vector of R6 class instances.

library(R6)

# define a class
Person <- R6Class("Person", list(
  name = NULL,
  initialize = function(name) self$name <- name
))

# create two instances of a class
Jack <- Person$new(name = "Jack")
Jill <- Person$new(name = "Jill")

I naively used %in% to check this, and it seems to have worked:

# yes
c(Jack) %in% c(Jack, Jill)
#> [1] TRUE

But it actually returns TRUE no matter the instance:

# also yes
c(Jack) %in% c(Jill)
#> [1] TRUE

So I had two questions:

  1. What is %in% actually matching that it always returns TRUE?
  2. How can I correctly check if an instance of R6 class is present in a vector of class instances?

Solution

  • R6 objects are environments, c(Jack) is a list containing an environment and %in% acts like this on lists of environments.

    e1 <- new.env()
    e2 <- new.env()
    list(e1) %in% list(e2)
    ## [1] TRUE
    

    Try identical

    sapply(c(Jack , Jill), identical, Jack)
    ## [1]  TRUE FALSE
    

    R6 objects have "R6" in their class vector so

    sapply(c(Jack, Jill, sin, 37), inherits, "R6")
    ## [1]  TRUE  TRUE FALSE FALSE