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:
a
to foo
foo
then changes the value of first element of a
to 4
in global environment 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
,
a
which is the original c(1, 2, 3)
foo
where the same thing that I explained above happensSo 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.