为什么我的R在动态作用域中运行?它不应该是词汇吗? [英] Why does my R run in dynamic scoping? Shouldn't it be lexical?

查看:101
本文介绍了为什么我的R在动态作用域中运行?它不应该是词汇吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在课堂上了解到R使用词法作用域,并在计算机上的R Studio中对其进行了测试,我得到了适合动态作用域而不是词法作用域的结果?难道这不应该在R中发生吗?我跑了:

I just learned in class that R uses lexical scoping, and tested it out in R Studio on my computer and I got results that fit dynamic scoping, not lexical? Isn't that not supposed to happen in R? I ran:

y <- 10
f <- function(x) {
  y <- 2
  y^3
}
f(3)

即使我的班级展示了这张幻灯片,f(3)仍然是4(2 ^ 3)而不是100(10 ^ 3):

And f(3) came out to be 4 (2^3) not 100 (10^3), even though my class presented this slide: http://puu.sh/pStxA/0545079dbe.png . Isn't that dynamic scoping? I may just be looking at this wrong, but is there a mode on a menu somewhere where you can switch the scoping to lexical, or what is happening?

推荐答案

您的代码已在函数本身内分配了y,在全局环境中要在y之前对其进行查找.

Your code has assigned y within the function itself, which is looked up before the y in the global environment.

这篇出色的文章( http://www.r-bloggers.com/environment-in-r/):评估函数时,R在一系列环境中查找范围内的任何变量.首先是评估环境,然后是函数的封闭环境,它将是全局环境用于工作空间中定义的功能."

From this excellent article (http://www.r-bloggers.com/environments-in-r/): "When a function is evaluated, R looks in a series of environments for any variables in scope. The evaluation environment is first, then the function’s enclosing environment, which will be the global environment for functions defined in the workspace."

以特定于您的情况的简单语言表示:调用变量"y"时,R在函数的环境中查找"y",如果找不到该变量,它将进入您的工作区.举例说明:

In simpler language specific to your case: when you call the variable "y", R looks for "y" in the function's environment, and if it fails to find one, then it goes to your workspace. An example to illustrate:

y <- 10

f <- function(x) {
  y^3
}

f(3)

将产生输出:

> f(3)
[1] 1000

这篇关于为什么我的R在动态作用域中运行?它不应该是词汇吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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