如果在泛型函数中定义变量,则该变量可用于该方法。例如:
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 from插入到方法评估环境中的变量列表。
/* 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 */
关于r - 泛型函数 R 中的作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27865582/