RJ-
RJ-

Reputation: 3037

Assignment of variables within function

I recently found a quirk in the R language and I am not sure if this is intended or a bug.

Below is an example:

# Simple print function
print.func <- function(n) {print(n)}

# Test it out
print.func(1:10)
[1]  1  2  3  4  5  6  7  8  9 10

# However, if we wrap an assignment into the function
print.func(a <- 1:10)

What I do not understand is that within the print.func, all assignments should be confined to the local function environment, but in this case, a gets assigned in the global environment.

I would expect this behaviour only if we do something like print.func(a <<- 1:10).

Any ideas why this happens?

Upvotes: 2

Views: 67

Answers (1)

Roland
Roland

Reputation: 132706

This is documented behavior.

See the R Language Definition Section 4.3.3:

It is also worth noting that the effect of foo(x <- y) if the argument is evaluated is to change the value of x in the calling environment and not in the evaluation environment of foo.

In your example the calling environment is the global environment.

Upvotes: 6

Related Questions