简体   繁体   中英

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? 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. Seemingly, the only difference is that a is used (but not defined) in a parent environment.

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:

  • It passes a to foo
  • foo then changes the value of first element of a to 4 in global environment
  • After that foo prints 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. 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. So the a will change to c(4, 2, 3) .

However when you call baz ,

  • It first prints a which is the original c(1, 2, 3)
  • Then it passes it to foo where the same thing that I explained above happens

So that's why the first print is the original a and the second is the modified one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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