简体   繁体   English

通用功能范围R

[英]Scope in generic functions R

If you define a variable inside a generic function, it is available to the method. 如果在通用函数中定义变量,则该变量可用于该方法。 For example: 例如:

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

But if the variable you define has the same name as the function parameter, this does not happen. 但是,如果您定义的变量与函数参数具有相同的名称,则不会发生这种情况。 It seems that R deletes that variable before calling the method: 似乎R在调用方法之前删除了该变量:

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

Could someone explain exactly what is going on here? 有人可以确切解释这里发生了什么吗?

The following comments from the C source file that defines do_usemethod at least hint at what's going on. C源文件中定义do_usemethod的以下注释至少暗示发生了什么。 See especially the second sentence of the second enumerated item. 尤其请参见第二个列举项目的第二句。

Basically, it looks like (due to dumb application of rule in that second point), the value of x does not get copied over because the C code checks to see if it's among the formals, sees that it is, and so excludes if from the list of variables inserted into the method's evaluation environment. 基本上,它看起来像(由于在第二点应用了愚蠢的规则),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 */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM