[英]Why does using a variable in a function change the value returned in R when using superassignment (<<-) operator?
Why do bar and baz behave differently?为什么 bar 和 baz 的行为不同? When bar is called both the value of a printed and the value of a in the global scope are the same, but when baz is called the printed value and the value in the global scope are different.
当调用 bar 时,打印的值和全局 scope 中的值是相同的,但是当调用 baz 时,打印的值和全局 scope 中的值不同。 Seemingly, the only difference is that a is used (but not defined) in a parent environment.
看起来,唯一的区别是 a 在父环境中使用(但未定义)。
a = 1:3
b = 4
foo <- function(a) {
a[1] <<- b
print(a)
}
bar <- function(a) {
foo(a)
}
baz <- function(a) {
a
foo(a)
}
bar(a) # 4 2 3
a # 4 2 3
a <- 1:3
baz(a) # 1 2 3
a # 1 2 3
Complex assignment operator <<-
changes the value of a variable in the parent environment.复杂赋值运算符
<<-
更改父环境中变量的值。 When bar
is called:当
bar
被调用时:
a
to foo
a
传递给foo
foo
then changes the value of first element of a
to 4
in global environment foo
然后在全局环境中将a
的第一个元素的值更改为4
foo
prints a
foo
打印a
> bar(a) # 4 2 3
[1] 4 2 3
The only thing to note here is, since foo
was created in global environment, it searches for the value of b
through lexical scoping in the environment where it was created which is again global environment.这里唯一需要注意的是,由于
foo
是在全局环境中创建的,它通过词法范围在创建它的环境中搜索b
的值,这也是全局环境。 Such is the case when foo
prints a
in the end, it again searches for its value in the environment where it was created which is global environment.当
foo
最后打印a
时就是这种情况,它再次在创建它的环境(即全局环境)中搜索它的值。 So the a
will change to c(4, 2, 3)
.所以
a
将变为c(4, 2, 3)
。
However when you call baz
,但是,当您致电
baz
时,
a
which is the original c(1, 2, 3)
a
这是原始的c(1, 2, 3)
foo
where the same thing that I explained above happensfoo
发生我上面解释的相同的事情So that's why the first print is the original a
and the second is the modified one.所以这就是为什么第一个打印是原始
a
而第二个是修改过的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.