R中的形式论证评估和词汇范围 [英] Formal Arguments Evaluation and Lexical Scoping in R

查看:67
本文介绍了R中的形式论证评估和词汇范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读Hadley Wickham的Advanced R,以便更好地了解R的机制以及它在幕后的工作方式.到目前为止,我很喜欢,而且一切都非常清楚,我尚未解决一个问题,这是我脑海中浮现的一个问题.我非常熟悉R的作用域规则,该规则确定如何将值分配给FREE VARIABLES,但是我一直在思考为什么R不能通过词法作用域来找到形式参数的值?考虑以下示例:

I have been reading Hadley Wickham's Advanced R in order to gain a better understanding of the mechanism or R and how it works behind the scene. I have so far enjoyed and everything is quite clear, there is one question that occupy s my mind for which I have not yet found an explanation. I am quite familiar with the scoping rules of R which determines how values are assigned to FREE VARIABLES, However I have been grappling with the idea that why R cannot find the value of a formal argument through lexical scoping? consider the following example:

y <- 4
f1 <- function(x = 2, y) {
  x*2 + y
}

f1(x = 3)

所以我想知道为什么R无法分配在调用者环境中定义的y值,并随后引发错误.我知道这听起来很怪异,但我在这里肯定会遗漏一些东西,但是如果您能为我提供一些解释,我将不胜感激.

So I would like to know why R cannot assign the value of y which is defined in the caller environment and subsequently throws an error. I know it may sound weird and I am definitely missing something here but I would appreciate it if you could provide some explanation for me.

我自己有一个假设,因为在调用函数时会为每个函数参数分配一个promise,并根据函数的评估环境或调用环境中的promise是否具有默认值或用户来对promise进行评估.定义的值,这里的两种情况都不成立,因此R不知道在哪里评估形式参数.

I myself have an assumption that since every function argument is assigned a promise when a function is called and a promise is either evaluated in the evaluation environment of a function or in the calling environment based on whether it has default value or a user defined value and here neither case is true so R doesn't know where to evaluate the formal argument.

另外一个令我困惑的问题是以下呼叫:

And also another confusing issue for me was the following call:

A <- 10.5
call("round", A)

在上述函数中,R可以为其形式参数A分配值10.5.

In the above function R can assign the value 10.5 to its formal argument A.

非常感谢您

推荐答案

您已经在 f1()中定义了 y ,只是没有将值绑定到该值.全局环境中的 y 是完全不同的变量.

You have defined y in f1(), you just haven't bound a value to it. The y that is in the global environment is a completely different variable.

这篇关于R中的形式论证评估和词汇范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆