通用函数R的范围

时间:2015-01-09 17:04:58

标签: r scope

如果在泛型函数中定义变量,则该方法可以使用该变量。例如:

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

有人可以准确解释这里发生了什么吗?

1 个答案:

答案 0 :(得分:4)

C source file that defines do_usemethod的以下评论至少暗示了正在发生的事情。特别参见第二个枚举项的第二句。

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

/* 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 */