2

The identical() function seems to give the correct answer, but the documentation doesn't explicitly discuss object references. The closest note in the documentation is:

Checking equality for two large, complicated objects can take longer if the objects are identical or nearly so, but represent completely independent copies.

Some examples of using identical():

QuickClass <- R6::R6Class("QuickClass",
  public = list(
   initialize = function(x) {
     private$px <- x
   }
   ),
   active = list(
     x = function(px) {
       if(missing(px)) return(private$px)
       else private$px <- px 
     }
   ),
   private = list(
     px = 0 
   )
)

> a <- QuickClass$new(1)
> identical(a, a)
[1] TRUE
> b <- a
> identical(a, b)
[1] TRUE
> c <- QuickClass$new(2)
> identical(a, c)
[1] FALSE
> d <- QuickClass$new(1)
> identical(a, d)
[1] FALSE

So, identical looks to do what is needed, I just want to check if there is a better way e.g. a specific function that just compares object references so may be faster and more directly applicable. identical() looks like it can resort to field-by-field comparisons.

Contrast clause: This question is similar to In R, how can I check if two variable names reference the same underlying object? - however that question is quite old (pre-R6 classes) and the answers discuss using low-level techniques that I would rather avoid.

Community
  • 1
  • 1
cbailiss
  • 1,304
  • 11
  • 21

1 Answers1

1

You could assign a random id for each new object and compare the ids.

library(R6)

MyClass <- R6Class(
  "MyClass",
  public = list(
    id = NULL,
    initialize = function(){
      self$id <- as.character(sample(1:10^6, 1))
    }
  )
)

MyClass$equal <- function(object1, object2){
  object1$id == object2$id
}

A <- MyClass$new()
B <- MyClass$new()
MyClass$equal(A, A)
# TRUE
MyClass$equal(A, B)
# FALSE
Gregor de Cillia
  • 7,397
  • 1
  • 26
  • 43
  • Thanks, this is a possible approach however I was wondering if there was a built-in/R6 function that say does a more basic comparison (like comparing memory locations). Also, using a random number could I suppose lead to collisions when sample() returns the same number for two different instances. But the idea of using a property could work e.g. if the id number was ever-increasing. – cbailiss Jun 21 '17 at 07:00
  • 1
    I agree that this approach has some downsides. Guaranteeing unique ids is certeinly possible by using a counter instead of an RNG. `all.equal.environment` is also a possible choice altough it compares instances on an objet level rather than an reference level (so memory locations are irrelevant) – Gregor de Cillia Jun 22 '17 at 11:35