'How to validate (e.g. check if a list contains etc.) R6 objects in R?

How to validate if R6 objects i.e. if an R6 objects equals another R6 object.

Let's have an example class, and then create an object (as done here: https://r6.r-lib.org/articles/Introduction.html)

> Person <- R6Class("Person",
+                   public = list(
+                       name = NULL,
+                       hair = NULL,
+                       initialize = function(name = NA, hair = NA) {
+                           self$name <- name
+                           self$hair <- hair
+                           self$greet()
+                       },
+                       set_hair = function(val) {
+                           self$hair <- val
+                       },
+                       greet = function() {
+                           cat(paste0("Hello, my name is ", self$name, ".\n"))
+                       }
+                   )
+ )
> ann <- Person$new("Ann", "black")
Hello, my name is Ann.

However, when we try to validate our object against itself, it is not possible:

> ann == ann
Error in ann == ann : 
  comparison (1) is possible only for atomic and list types

Then we can create a list containing our objects, and check whether our object is on that list, but...

> listOfAnns <- list(ann, ann, ann, ann)
> ann %in% listOfAnns
Error in match(x, table, nomatch = 0L) : 
  'match' requires vector arguments

...it does not work.

So is there a way to do this type of validation in R?



Solution 1:[1]

You can use identical():

ann <- Person$new("Ann", "black")
#> Hello, my name is Ann.

jo <- Person$new("jo", "blonde")
#> Hello, my name is jo.

identical(ann, ann)
#> [1] TRUE

identical(ann, jo)
#> [1] FALSE

Created on 2022-02-21 by the reprex package (v2.0.1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1