我怀疑我不了解setRefClass
R 中的所有方面。假设我有一个setRefClass
初始化的实例。我想创建变量X
,以便该变量等于实例的副本或引用setRefClass
. 有没有区别:
x = InstanceOfsetRefClass
和
x <<- InstanceOfsetRefClass
我不完全理解,我的代码似乎有奇怪的行为。
谢谢你的帮助
我怀疑我不了解setRefClass
R 中的所有方面。假设我有一个setRefClass
初始化的实例。我想创建变量X
,以便该变量等于实例的副本或引用setRefClass
. 有没有区别:
x = InstanceOfsetRefClass
和
x <<- InstanceOfsetRefClass
我不完全理解,我的代码似乎有奇怪的行为。
谢谢你的帮助
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