R: Change the fields' (slots') values of the class assigning a value to some other field

不想你离开。 提交于 2019-12-08 09:39:20

问题


Assgning a value to one field, how can I make the other fields changing.

Consider the following ReferenceClass object:

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

Now create the instance of the class

c<-C$new() 

This command

c$seta(10)

will result in that c$a is 10 and c$b is 20.

So it actually works, however, I want to achieve this result by the command

c$a<-10

(i.e. after that I want c$b to be equal to 20 as defined in the class in the logic of seta() function)
How can I do it?


回答1:


I think you are looking for accessor functions, which are described in detail in ?ReferenceClasses. This should work:

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

It does have the side effect that a new value, x is now in the environment c (the class object), but it is 'hidden' from the user in the sense that just printing c will not list x as a field.



来源:https://stackoverflow.com/questions/11353135/r-change-the-fields-slots-values-of-the-class-assigning-a-value-to-some-oth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!