【问题标题】:R: Change the fields' (slots') values of the class assigning a value to some other fieldR:更改类的字段(插槽)值,将值分配给其他字段
【发布时间】:2012-07-05 21:58:21
【问题描述】:

为一个字段赋值,如何让其他字段发生变化。

考虑以下ReferenceClass 对象:

C<-setRefClass("C", 
      fields=list(a="numeric",b="numeric")
      , methods=list(
      seta = function(x){
      a<<-x
      b<<-x+10
      cat("The change took place!")
      }
      ) # end of the methods list
      ) # end of the class

现在创建类的实例

c<-C$new() 

这个命令

c$seta(10)

将导致 c$a 为 10,c$b 为 20。

所以它确实有效,但是,我想通过命令来实现这个结果

c$a<-10

(即之后我希望 c$b 等于 20,如 seta() 函数逻辑中的类中定义的那样)
我该怎么做?

【问题讨论】:

  • 哦不!这不是R5级别! stackoverflow.com/questions/5137199/…
  • 因此正确的名称实际上是“参考类”,对吧?
  • 没错。不幸的是,它没有那么紧凑,但生活就是这样。
  • 可能涉及到的人,请说明您对此问题投反对票的原因,这将有助于我避免将来发布不适当的问题。
  • 投反对票的不是我,但可以通过添加 [reference-class] 标记并将R5 类编辑为Reference Class 来改进问题

标签: r reference-class


【解决方案1】:

我认为您正在寻找访问器函数,在?ReferenceClasses 中有详细描述。这应该有效:

C<-setRefClass("C", 
    fields=list(
        a=function(v) {
              if (missing(v)) return(x)
              assign('x',v,.self)                    
              b<<-v+10
              cat ('The change took place!')
            }
       ,b="numeric"
    )
    ,methods=list(
        initialize=function(...)  {
             assign('x',numeric(),.self)
            .self$initFields(...)
        } 
    )
)

c<-C$new()
c$a
# numeric(0)
c$a<-3
# The change took place!
c$b
# 13
c$a
# 3

它确实有一个副作用,一个新值 x 现在在环境 c(类对象)中,但它对用户是“隐藏”的,因为只打印 c 会不将 x 列为字段。

【讨论】:

  • 命令“c
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-02
  • 2021-04-29
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多