1

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.

Hong Ooi
  • 56,353
  • 13
  • 134
  • 187

1 Answers1

1

This isn't possible currently with R6 classes.

There is a discussion on this topic at: https://github.com/r-lib/R6/issues/153

cbailiss
  • 1,304
  • 11
  • 21