A Diversion on Binding Values to Symbol

When R tries to bind a value to a symbol,it searches through a series of environments to find the appropriate value.When you are working on the command line and need to retrieve the value of an Robject, the order is roughly

1. Search the global environment for asymbol name matching the one requested.

2. Search the namespaces of each of thepackages on the search list

The search list can be found by using thesearch function.

>search() [1] ".GlobalEnv" "package:stats""package:graphics" [4] "package:grDevices""package:utils" "package:datasets" [7]"package:methods" "Autoloads" "package:base"

Binding Values to Symbol

The global environment or the user’sworkspace is always the first element of the search list and

the base package is always the last.

The order of the packages on the searchlist matters!

User’s can configure which packages getloaded on startup so you cannot assume that there will

be a set list of packages available.

When a user loads a package with librarythe namespace of that package gets put in position

2 of the search list (by default) andeverything else gets shifted down the list.

Note that R has separate namespaces forfunctions and non-functions so it’s possible to have an

object named c and a function named c.

Scoping Rules

The scoping rules for R are the mainfeature that make it different from the original S language. The scoping rulesdetermine how a value is associated with a free variable in a function

R uses lexical scoping or static scoping. Acommon alternative is dynamic scoping.

Related to the scoping rules is how R usesthe search list to bind a value to a symbol

Lexical scoping turns out to beparticularly useful for simplifying statistical computations

Lexical Scoping

Consider the following function.

f<- function(x, y) {

x^2 + y / z

}

This function has 2 formal arguments x andy. In the body of the function there is another symbol z. In this case z iscalled a free variable. The scoping rules of a language determine how valuesare assigned to free variables. Free variables are not formal arguments and arenot local variables (assigned insided the function body).

Lexical scoping in R means that:

the values of free variables are searchedfor in the environment in which the function was defined.

What is an environment?

An environment is a collection of (symbol,value) pairs, i.e. x is a symbol and 3.14 might be its

value.

Every environment has a parent environment;it is possible for an environment to have multiple

“children”

the only environment without a parent isthe empty environment

A function + an environment = a closure orfunction closure

Searching for the value for a freevariable:

If the value of a symbol is not found inthe environment in which a function was defined, then the

search is continued in the parentenvironment.

The search continues down the sequence ofparent environments until we hit the top-level

environment; this usually the globalenvironment (workspace) or the namespace of a package.

After the top-level environment, the searchcontinues down the search list until we hit the empty

environment. If a value for a given symbolcannot be found once the empty environment is

arrived at, then an error is thrown.

Why does all this matter?

Typically, a function is defined in theglobal environment, so that the values of free variables are

just found in the user’s workspac

This behavior is logical for most peopleand is usually the “right thing” to do

However, in R you can have functionsdefined inside other functions

-Languages like C don’t let you do this

Now things get interesting — In this casethe environment in which a function is defined is the

body of another function!

make.power<- function(n) {

pow <- function(x) {

x^n

}

pow

}

This function returns another function asits value

>cube <- make.power(3)

>square <- make.power(2)

>cube(3)

[1]27

>square(3)

[1] 9

Exploring a Function Closure

What’s in a function’s environment?

>ls(environment(cube))

[1]"n" "pow"

>get("n", environment(cube))

[1] 3

>ls(environment(square))

[1]"n" "pow"

>get("n", environment(square))

[1] 2

Lexical vs. Dynamic Scoping

y<- 10

f<- function(x) {

y <- 2

y^2 + g(x)

}

g<- function(x) {

x*y

}

With lexical scoping the value of y in thefunction g is looked up in the environment in which the

function was defined, in this case theglobal environment, so the value of y is 10.

With dynamic scoping, the value of y islooked up in the environment from which the function was

called (sometimes referred to as thecalling environment).

- InR the calling environment

So the value of y would be 2.

When a function is defined in the globalenvironment and is subsequently called from the global environment, then thedefining environment and the calling environment are the same. This cansometimes give the appearance of dynamic scoping.

>g <- function(x) {

+ a<- 3

+x+a+y

+ }

>g(2)

Errorin g(2) : object "y" not found

>y <- 3

>g(2)

[1] 8

Consequences of Lexical Scoping

In R, all objects must be stored in memory

All functions must carry a pointer to theirrespective defining environments, which could be

anywhere

In S-PLUS, free variables are always lookedup in the global workspace, so everything can be

stored on the disk because the “definingenvironment” of all functions is the same.

R Programming week2 Functions and Scoping Rules的更多相关文章

  1. R Programming week2 Control Structures

    Control Structures Control structures in R allow you to control the flow of execution of the program ...

  2. Coursera系列-R Programming第二周

    博客总目录,记录学习R与数据分析的一切:http://www.cnblogs.com/weibaar/p/4507801.html  --- 好久没发博客 且容我大吼一句 终于做完这周R Progra ...

  3. Coursera系列-R Programming第三周-词法作用域

    完成R Programming第三周 这周作业有点绕,更多地是通过一个缓存逆矩阵的案例,向我们示范[词法作用域 Lexical Scopping]的功效.但是作业里给出的函数有点绕口,花费了我们蛮多心 ...

  4. 让reddit/r/programming炸锅的一个帖子,还是挺有意思的

    这是原帖 http://www.reddit.com/r/programming/comments/358tnp/five_programming_problems_every_software_en ...

  5. 解决proto文件转换时提示“Note that enum values use C++ scoping rules, meaning that enum values are siblings of their type, not children of it. ”

    前言: 想将.proto文件转换成.pb文件时一直报错,一开始以为是文件编码格式的问题,后来将文件改成windows下的utf-8格式后,又出现了新的报错(见下图).百度了很久,才找到解决方法. &q ...

  6. R Programming week 3-Loop functions

    Looping on the Command Line Writing for, while loops is useful when programming but not particularly ...

  7. [R] [Johns Hopkins] R Programming 作業 Week 2 - Air Pollution

    Introduction For this first programming assignment you will write three functions that are meant to ...

  8. Standard C++ Programming: Virtual Functions and Inlining

    原文链接:http://www.drdobbs.com/cpp/standard-c-programming-virtual-functions/184403747 By Josée Lajoie a ...

  9. R Programming week 3-Debugging

    Something’s Wrong! Indications that something’s not right message: A generic notification/diagnostic ...

随机推荐

  1. C控制台密码输入:输入一个字符显示一个星号

    要在c控制台中输入一个字符显示一个星号, 则不能用"stdio.h'提供的库函数,因为它们都是带回显的,比如getchar() getchar()用来接收输入的字符串,输入一个字符就回显一个 ...

  2. 设计模式-(9)中介者模式(swift)

    在对象去耦合的模式中,有两种模式:中介者模式,观察者模式 一,概念 用一个中介对象来封装一系列的对象交互.中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互. 这个 ...

  3. HEX文件格式学习笔记

    这也是一篇学习摘抄:原文地址:http://blog.csdn.net/syrchina/article/details/7004998        为了编写一个可以按照自己的要求进行ISP的程序, ...

  4. caioj1421&&hdu2167: [视频]【状态压缩】选数

    %hz大佬..这道题的状态压缩简直匪夷所思(其实是我孤陋寡闻,而且我以前的博客竟然写了这题..水啊) 嗯这题可以发现,我们可以用一个二进制表示一行的状态,1表示选0反之,可以发现行与行之间可选的范围是 ...

  5. Consistent Hashing算法

    前几天看了一下Memcached,看到Memcached的分布式算法时,知道了一种Consistent Hashing的哈希算法,上网搜了一下,大致了解了一下这个算法,做下记录. 数据均衡分布技术在分 ...

  6. sqlite支持linq

    A small library to easily access SQLite databases from .NET/Mono/MonoTouch applications In order to ...

  7. MySQL-Tool:Navicate 安装

    ylbtech-MySQL-Tool:Navicate 安装 1.返回顶部 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 2. 激活返回顶部 1. 2. 3. 4. 5. 6. 7. ...

  8. c语言struct和c++的class的暧昧

    c语言风格的封装 数据放在一起,以引用和指针的方式传给行为c++ 认为封装不彻底 1数据和行为分开 对外提供接口 2没有权限设置 看看struct的一个例子 //data.h //c语言风格的封装 数 ...

  9. ASP.NET Core MVC 打造一个简单的图书馆管理系统 (修正版)(五)外借/阅览图书信息的增删改查

    前言: 本系列文章主要为我之前所学知识的一次微小的实践,以我学校图书馆管理系统为雏形所作. 本系列文章主要参考资料: 微软文档:https://docs.microsoft.com/zh-cn/asp ...

  10. PostgreSQL完整备份与还原过程

    1. 备份10.12.2.100PC机(服务器)上的数据库(仅备份数据库和对应的数据库里面各表的结构): pg_dump -h 10.12.2.100 -U postgres -p 8101 -d t ...