全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 R语言论坛
1707 1
2010-10-30

The form of the assignment expression is generally left-hand-side <- right-hand-side. Where the left-hand-side, when evaluated, yields a symbol while the right-hand-side yields a value.

The assignment operator, <-, is overloaded. An operator is said to be overloaded if it performs more than one task. In R and S the assignment operator performs two tasks. If the left-hand side is a symbol that already exists in the current environment, then the value of that symbol is changed to the right-hand side. If the symbol does not exist in the current environment, then it is created and the value of the right-hand side is assigned to it.

Most programming languages separate these two tasks. Overloading them can make programming easier but can also create serious problems in writing compilers and in understanding the code. Consider the following unusual, but legal, code segment:

foo <-

function(x) {

if (x < 10)

y <- 12

x + y

}

If

>foo(11)

错误于foo(11) : 找不到对象'y'

> foo(5)

[1] 17

Now, one cannot determine whether y is a local variable or a global variable until the function is evaluated. If x<10, then y in x+y is a local variable and otherwise it is a global variable.

However, the second type of assignment, <<- can deal with this problem.

In R, the semantics of the operator are such that starting with the parent of the current environment and searching up through the enclosing environments the symbol on the left-hand side is sought. If it is found then the value of the right hand side is associated with it. If it is not found once the top-level environment has been searched, then the symbol on the left-hand side is assigned to it.

foo <-

function(x) {

if (x < 10)

y <<- 12

x + y

}

> foo(5)

[1] 17

> foo(11)

[1] 23


PS

An environment is a collection of symbols and associated values.

A function closure is a function together with an environment.

The symbols that occur in the body of a function can be divided into two groups; bound variables and free variables. The formal parameters of a function are those occurring in the argument list of the function. Any variable in the body of the function that matches one of the formal parameters is bound to that formal parameter. Local variables, those whose values are determined by the evaluation of expressions in the body of the functions, are bound to the values of the expressions. All other variables are called free variables. At the time that the function is evaluated, a binding must be obtained for all variables

二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

全部回复
2014-12-29 17:37:11
这样看贴进来的内容,感觉不到其他差别
除了下面的y用了<<-
应该是换行之后空格的问题吧
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群