简体   繁体   English

可以为R6 /引用类定义索引方法吗?

[英]Possible to define indexing methods for R6/reference classes?

I have an R6 class that is basically a wrapper around a matrix-like object. 我有一个R6类,基本上是一个类似矩阵的对象的包装器。 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. 虽然这是针对R6的,但也欢迎使用引用类的答案。

This isn't possible currently with R6 classes. 目前R6类无法实现。

There is a discussion on this topic at: https://github.com/r-lib/R6/issues/153 关于此主题的讨论,位于: https : //github.com/r-lib/R6/issues/153

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM