I am currently working on a project where I need to build an R6 class in R that can be initialized in more than one way. I am wondering what the best way is to go about it. Is it possible to overload the $new()
function? Or do I need to define a helper function?
As a motivating example: I would like to have two constructors for an R6 class MyClass
with a field names
that can be initialized using either using vector variable_names
or a integer n_variables
(in which case it initializes a default vector of names).
The functionality should work like this:
#define the class (only has a constructor that accepts a vector of names)
myClass <- R6Class("myClass",
public = list(
names = NA,
initialize = function(names) {
if (!missing(names)) self$names <- names
})
)
#create a test object using a vector of names
variable_names = c("x","y")
a = myClass$new(variable_names)
a$names
#> [1] "x y"
#everything after here does not actually work (just to illustrate functionality)
n_variables = 2;
b = myClass$new(n_variables)
b$names
#> [1] "v1 v2"
I took a look through the Introductory vignette, but there doesn't seem to be a clear way to do this.
Ideally, I am looking for a solution that does not force me to name the arguments (i.e. so I do not have to do something like myClass$new(names=variable_names)
) and that lets me easily check that the inputs are valid.