0

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?

Daniel Krizian
  • 4,586
  • 4
  • 38
  • 75
Max Li
  • 5,069
  • 3
  • 23
  • 35
  • 2
    Oh no! It's not an R5 class! http://stackoverflow.com/questions/5137199/what-is-the-significance-of-the-new-reference-classes – Ari B. Friedman Jul 05 '12 at 22:10
  • it follows that the proper name is actually "Reference Class", right? – Max Li Jul 05 '12 at 22:21
  • Exactly. Unfortunately it's not as compact, but such is life. – Ari B. Friedman Jul 06 '12 at 00:06
  • to whom it may concern, please mention the reasons for which you downvote this question, this would help me to avoid posting inappropriate questions in the future. – Max Li Jul 09 '12 at 13:06
  • it wasn't me who downvoted, but the question can be improved by adding [reference-class] tag to it, and editing `R5` class to `Reference Class` – Daniel Krizian Jan 09 '14 at 14:27

1 Answers1

3

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.

nograpes
  • 18,623
  • 1
  • 44
  • 67
  • the command "c<-C$new()" results in the error message "Error in function (v) : object 'x' not found" – Max Li Jul 09 '12 at 21:22