1

I need to get the name of the R6 class variable from inside the class. Can I do that? - like in example below:

  Simple <- R6Class(  "Simple",
                      public = list(
                        myname = NA,
                        dt = NA, 
                        initialize = function () {
                          self$myname = substitute(self)
                        }
                      )              
  )
  mysimple <- Simple$new()  
  mysimple$myname 

This returns self. And i want this to return mysimple.

This would be useful for storing a class variable with saveRDS() and then restoring it with saveRDS()

IVIM
  • 2,167
  • 1
  • 15
  • 41
  • Have you considered using `save(mysimple, file=)` instead? Roughly speaking, `.RData` files save name-value pairs, while `.rds` files only save values. – Mikael Jagan Mar 04 '23 at 00:37

1 Answers1

1

Yes, you can use class(self)[1] e.g.

Simple <- R6Class(
  "Simple",
  public = list(
    getClass = function(){
      class(self)[1]
    }
  )
)

mysimple <- Simple$new()

mysimple$getClass()

Based on the solution in the GitHub issues: https://github.com/r-lib/R6/issues/135

nrennie
  • 1,877
  • 1
  • 4
  • 14