简体   繁体   English

为什么在使用超赋值 (<<-) 运算符时,在 function 中使用变量会更改 R 中返回的值?

[英]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被调用时:

  • It passes a to foo它将a传递给foo
  • foo then changes the value of first element of a to 4 in global environment foo然后在全局环境中将a的第一个元素的值更改为4
  • After that 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时,

  • It first prints a which is the original c(1, 2, 3)它首先打印a这是原始的c(1, 2, 3)
  • Then it passes it to foo where the same thing that I explained above happens然后它将它传递给foo发生我上面解释的相同的事情

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM