0

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?

IVIM
  • 2,167
  • 1
  • 15
  • 41
  • This could be the answer: https://stackoverflow.com/questions/45331703/is-it-possible-to-change-the-value-of-r6-function-good-style-oop-programming/45334556#45334556. I need to include `self` in function(self) – IVIM Feb 28 '23 at 17:11

1 Answers1

0

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
> 
IVIM
  • 2,167
  • 1
  • 15
  • 41