如果在泛型函数内定义变量,则该方法可以使用该变量.例如:
g <- function(x) {
y <- 2
UseMethod("g")
}
g.default <- function() y
g()
[1] 2
Run Code Online (Sandbox Code Playgroud)
但是,如果您定义的变量与函数参数具有相同的名称,则不会发生这种情况.似乎R在调用方法之前删除了该变量:
g <- function(x) {
x <- 2
UseMethod("g")
}
g.default <- function() x
g()
Error in g.default() : object 'x' not found
Run Code Online (Sandbox Code Playgroud)
有人能解释到底发生了什么吗?
以下来自定义的 C 源文件的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 */
Run Code Online (Sandbox Code Playgroud)