I have an R6 class that is basically a wrapper around a matrix-like object. I'd like to define a method for my class that lets me index and subset elements of the matrix directly.
At the moment, my code looks something like this:
cls <- R6Class("cls", public=list(
initialize=function(...)
{
private$mat <- matrix(...)
private$mat
}),
private=list(mat=NULL)
)
"[.cls" <- function(x, ...)
{
x$.__enclos_env__$private$mat[...]
}
z <- cls$new(1:25, 5, 5)
z[1, 1]
# [1] 1
However, this requires creating a top-level [
method that then directly accesses the private members of my class. I'd like to avoid this, if possible.
I tried adding a method within my class, but it doesn't work:
cls <- R6Class("cls", public=list(
initialize=function(...)
{
private$mat <- matrix(...)
private$mat
},
"["=function(x, ...)
{
"["(private$mat, ...)
}),
private=list(mat=NULL)
)
z[1, 1]
# Error in z[1, 1] : object of type 'environment' is not subsettable
Is there a way to do this without violating encapsulation?
While this is for R6, answers that use reference classes are also welcome.