How to change public R6 class method from outside of the class?

96 Views Asked by At

I'd like to be able to redefine a public method in my R6 class (so that it changes according to the type of data that the class holds) - like below

library(R6)
Simple <- R6Class(
  "Simple",
  public = list( 
    dt = mtcars,
    my.print = function (){
      print(self$dt$mpg)
    }
  )
)
s <- Simple$new()
s$my.print()

s$dt <- iris
s$my.print() <- function() {
  print(self$dt$Species)
}

The code above gives error:

Error in s$my.print() <- function() { : 
  invalid (NULL) left side of assignment

Alternatively, i know I can do this:

Simple$set("public", "my.print2", function {
  print(self$dt$Species) } ) 

But this is also not suitable as then I would have to reinitialize my classes every time I do this.

Is there a proper way to so that?

1

There are 1 best solutions below

0
IVIM On

With idea taken from dynamically add function to r6 class instance that how we can achieve the desired effect.

It's a bit tricky, as you need to take the note of the following:

  • first, you need declare your function as a class member variable, NOT as method (function)
  • Then this variable will become a function, when you assign is as such
  • This function receives the input parameter - the class itself (self)
Simple <- R6Class(
  "Simple",
  public = list( 
    dt = mtcars,
    my.print = NULL
  )
)

s <- Simple$new()
s$my.print
s$my.print(s)

s$dt <- iris
s$my.print <- function(self) {
  print(self$dt$Species %>% unique)
}
s$my.print
s$my.print(s)

The output of the above code is below:

> Simple <- R6Class(
+   "Simple",
+   public = list( 
+     dt = mtcars,
+     my.print = NULL 
+   )
+ )
> s <- Simple$new()
> s$my.print
NULL
> s$my.print(s)
Error: attempt to apply non-function
> s$my.print
NULL
> s$my.print(s)
Error: attempt to apply non-function
> s$dt <- iris
> s$my.print <- function(self) {
+   print(self$dt$Species %>% unique)
+ }
> 
> s$my.print
function(self) {
  print(self$dt$Species %>% unique)
}
> s$my.print(s)
[1] setosa     versicolor virginica 
Levels: setosa versicolor virginica
>