Reputation: 116
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
Upvotes: 3
Views: 57
Reputation: 21918
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 environmentfoo
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.
A resume of our discussion in comments:
baz
to be then passed to foobaz
is like using print(a) so whatever is printed is the result of what baz
does not foo contrary to what I explain abovebaz <- function(a) { foo(a) } and baz(c(1,2,3)
to better differentiate between the object a
and argument a
Upvotes: 3