函数内变量的赋值

Assignment of variables within function

我最近在 R 语言中发现了一个怪癖,我不确定这是有意为之还是一个错误。

下面是一个例子:

# 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)

我不明白的是,在print.func中,所有的赋值都应该限制在局部函数环境中,但是在这种情况下,a是在全局环境中赋值的。

只有当我们做类似 print.func(a <<- 1:10).

的事情时,我才会期望这种行为

知道为什么会这样吗?

这是记录在案的行为。

参见 R 语言定义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.

在您的示例中,调用环境是全局环境。