通用函数 R 中的作用域

Scope in generic functions R

如果您在泛型函数中定义了一个变量,则它可用于该方法。例如:

g <- function(x) {
  y <- 2
  UseMethod("g")
}
g.default <- function() y
g()
[1] 2

但如果你定义的变量与函数参数同名,则不会出现这种情况。似乎 R 在调用方法之前删除了该变量:

g <- function(x) {
  x <- 2
  UseMethod("g")
}
g.default <- function() x
g()
Error in g.default() : object 'x' not found

有人能解释一下到底是怎么回事吗?

C source file that defines do_usemethod 的以下评论至少暗示了正在发生的事情。具体见第二条列举项第二句

基本上,看起来(由于在第二点中对规则的愚蠢应用),x 的值没有被复制,因为 C 代码检查它是否在形式中,发现它是,因此从插入方法评估环境的变量列表中排除 if。

/* usemethod - calling functions need to evaluate the object
* (== 2nd argument). They also need to ensure that the
* argument list is set up in the correct manner.
*
* 1. find the context for the calling function (i.e. the generic)
* this gives us the unevaluated arguments for the original call
*
* 2. create an environment for evaluating the method and insert
* a handful of variables (.Generic, .Class and .Method) into
* that environment. Also copy any variables in the env of the
* generic that are not formal (or actual) arguments.
*
* 3. fix up the argument list; it should be the arguments to the
* generic matched to the formals of the method to be invoked */