1

I suspect i am not understanding all the aspects of setRefClass in R. Lets say I have an instance of a setRefClass initialized. I want to create the variable X so that this variable is equal to a copy of the instance or refers to the instance of setRefClass. Is there a difference between:

x = InstanceOfsetRefClass

and

x <<- InstanceOfsetRefClass

I don't fully understand and it seems I have strange behavior in my code.

Thanks for your help

Arun
  • 116,683
  • 26
  • 284
  • 387
pam
  • 676
  • 1
  • 7
  • 27
  • Not probably for this question, but in general, I think reading [**this wiki**](https://github.com/hadley/devtools/wiki/R5) should be helpful. – Arun Mar 21 '13 at 10:12

1 Answers1

2

I don't think your problem is anything to do with reference classes, rather it's about scope. Consider the following example. We start by removing all variables from our workspace and create a definition for A:

rm(list=ls())
A = setRefClass("A", fields=list(x="numeric"))

Next we create and call the function f:

f = function() {
  x1 = 1
  a1 = A$new(x=10)
  x2 <<- 2
  a2 <<- A$new(x=10)
}
f()

The key difference between <<- and = is

The operators '<<-' and '->>' are normally only used in functions, and cause a search to made through parent environments for an existing definition of the variable being assigned. If such a variable is found (and its binding is not locked) then its value is redefined, otherwise assignment takes place in the global environment.

From the help page: ?"<<-"

So variables created using = aren't found in the global enviroment

R> x1
Error: object 'x1' not found
R> a1
Error: object 'a1' not found

but the other variables are:

R> x2
[1] 2
R> a2
Reference class object of class "A"
Field "x":
[1] 10
csgillespie
  • 59,189
  • 14
  • 150
  • 185
  • ok so i think i am better off using = inside a function not to mess with the GlobalEnv and create conflict in case to variables would have the same name? – pam Mar 21 '13 at 11:02
  • @user1176316 Yes *but* within the reference object you'd use `<<-` to up date the variables in the fields. See the example at the bottom of `?setRefClass` – csgillespie Mar 21 '13 at 11:14
  • I agree. I sometimes encounter "local assignment to field name will not change the field" trying to use create a variable inside a method in the setRefClass. I am not sure what it means. – pam Mar 21 '13 at 11:17
  • You would get this error if you used `=` on a variable in a field. – csgillespie Mar 21 '13 at 11:23
  • One last question. If you want to use a variable inside a methods of a setRefClass, you do it the standard way ? " x = 1 "? – pam Mar 21 '13 at 12:08
  • Yes, unless you want it to be persistent. – csgillespie Mar 21 '13 at 12:15