R:在对象生成器中使用主动绑定来有条件地向 R6 对象添加新类 [英] R: Use active binding in object generator to conditionally add new class to R6 objects

查看:72
本文介绍了R:在对象生成器中使用主动绑定来有条件地向 R6 对象添加新类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 R6 对象生成器:

I have a simple R6 object generator:

thing <- R6Class("youngThing",
                 private = list(
                   ..age = 0),
                 active = list(
                   age = function(){
                     private$..age <- private$..age + 1
                     private$..age
                   }
                 )
)

这给了我一个简单的 R6 对象,其中 ..age 在每次调用活动 age 字段时增加 1:

That gives me a simple R6 object, where ..age increases by 1 every time the active age field is called:

a_thing <- thing$new()

a_thing$age
# [1] 1

我希望 a_thing 的对象类在给定私有字段 ..age 的阈值的情况下发生变化,如下所示:

I want the object class of a_thing to change given a threshold value of the private field ..age, like this:

class(a_thing)
# [1] "youngThing" "R6"

for(timestep in 1:10){
  if(a_thing$age >5 & ! inherits(a_thing, "olderThing")){
    class(a_thing) <- c("olderThing", class(a_thing))
  }
}

class(a_thing)
# [1] "olderThing" "youngThing" "R6" 

但是,我希望这发生在对象中.有没有办法将它作为活动绑定包含在对象生成器中,以便从它创建的任何对象都内置此功能?

However, I want this to happen within the object. Is there a way to include this as an active binding in the object generator, so that any object created from it will have this functionality built-in?

注意.最好将阈值类添加到对象中;它不会取代现有的类.

NB. It is preferred that the threshold class is added to the object; that it does not replace the existing classes.

推荐答案

您可以更改self的类.

library(R6)

thing <- R6Class(
  "youngThing",
  private = list(..age = 0),
  active = list(
    age = function() {
      private$..age <- private$..age + 1

      if(private$..age > 5 && !inherits(self, "olderThing")){
        class(self) <- c("olderThing", class(self))
      }
      private$..age
    }
  )
)

a_thing 有它的原始类,而 age <= 5.

a_thing has it's original class while age <= 5.

a_thing <- thing$new()

a_thing$age; a_thing$age; a_thing$age; a_thing$age; a_thing$age
#> [1] 2
#> [1] 3
#> [1] 4
#> [1] 5

class(a_thing)
#> [1] "youngThing" "R6" 

一旦超过5,它就会更新.

Then it updates once it goes over 5.

a_thing$age
#> [1] 6

class(a_thing)
#> [1] "olderThing" "youngThing" "R6" 

这篇关于R:在对象生成器中使用主动绑定来有条件地向 R6 对象添加新类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆