Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static methods in R6 classes

Tags:

r

r6

Is there a way to add static methods to R6 classes? For example, a function that can be called like

MyClass$method()

Instead of

myinstance <- MyClass$new()
myinstance$method()
like image 577
Abiel Avatar asked Mar 07 '15 15:03

Abiel


People also ask

What is an R6 class?

R6 is an implemention of encapsulated object-oriented programming for R, and is a simpler, faster, lighter-weight alternative to R's built-in reference classes. This style of programming is also sometimes referred to as classical object-oriented programming. Some features of R6: R6 objects have reference semantics.

What is Self in R6?

From the "Introduction to R6 classes" vignette (emphasis mine): self. Inside methods of the class, self refers to the object. Public members of the object (all you've seen so far) are accessed with self$x. private.

How would you create a new R6 class?

Create a new R6 class object that on multipication of numbers. The class name and the result of class must be same always, as the R6Class() returns a R6 object that defines the class. We can then construct a new object from the class using the new() method which is accessed using the $ operator.


2 Answers

I'm not an expert on R6 but since every R6 class is an environment, you can add anything you want to this environment.

Like:

MyClass$my_static_method <- function(x) { x + 2}
MyClass$my_static_method(1)
#[1] 3

But the method will not work on the instance of the class:

instance1 <- MyClass$new()
instance1$my_static_method(1)
# Error: attempt to apply non-function

You should be careful with the existing objects in the class environment. To see what is already defined use ls(MyClass)

like image 132
bergant Avatar answered Oct 06 '22 13:10

bergant


I have used a workaround for the solution. You can access the methods without creating the instance by calling MyClass$public_methods$my_static_method(). To restrict the calls without the instance, I have made self as an argument in all of the methods.

like image 22
user2855892 Avatar answered Oct 06 '22 14:10

user2855892