7

为环境中的名称赋值和设置变量的环境有什么区别?我无法从文档中弄清楚。

例如:

MyTestFunc = function(x)
{
    myVal = "abcde"

    # what is this doing?  why is myVal not in the global environment after 
    # this call? I see it adds an environment attribute to the variable, 
    # but what good is that?
    environment(myVal) = globalenv()

    assign( "myVal" , myVal , envir = globalenv() )

    # this seems to copy graphics:::rect to the current environment which seems 
    # to contradict the behavior of environment( myVal ) above
    environment( rect ) = environment()

    # this seems to do the same thing
    assign( "rect" , rect , envir = globalenv() )
}

# this prints out rect, but shows <environment: namespace: graphics>!
rect
4

2 回答 2

6

assign 函数只是将名称绑定到指定环境中的值。

但是环境替换函数做了两件事:它的主要目的是改变函数闭包的环境。该环境是函数的主体代码查找全局变量和函数的地方。通常,此环境是定义函数的环境(因此,如果您在提示符处定义它,它将使用 globalenv)。作为“奖励”,它只是为其他对象类型分配 .Environment 属性。这对于大多数对象来说是非常无用的,但公式使用。

第二件事是它几乎与任何其他替换函数一样工作:如果名称存在于当前环境中,它直接修改它,否则它创建一个本地副本并修改它。因此,在您的情况下,它会制作 rect 函数的本地副本并更改其环境。原来的功能保持不变。

# showing names replacement behavior
f <- function() {
  names(letters) <- LETTERS
  letters # the local modified copy
}
f() # prints changed letters
letters # unchanged
于 2011-12-27T14:55:39.727 回答
1

Inside a function you asked and executed:

 # what is this doing?  why is myVal not in the global environment after this call?
    # I see it adds an environment attribute to the variable, but what good is that?
    environment(myVal) = globalenv()

So you didn't really do anything to the myVal object named "abcde" that was in the function. You instead created a new environment named "abcede" inside the function's environment. You then executed:

assign( "myVal" , myVal , envir = globalenv() )

It created a variable named "myVal" with the character mode value of "abcde" gathered from the local function environment, and put it into the global environment. It does now have an attribute named ".Environment". However, it remains unclear what your goals are, since environments are designed to be used to define the scope of functions. Assigning an environment to a data object is just weird. Variables are in environments, but there wouldn't seem to be a useful purpose in setting the environment of a variable. So I think the answer to your question: ...what good is that?" should be "it's not any good."

于 2011-12-26T16:30:39.760 回答