The different ways of declaring objects in R
This question already has an answer here:
In some sense = and <- are equivalent, but the latter is preferred because = is also overwritten to specify default arguments (where <- will not work).
As for <<- , it is trickier and not recommended. In R, every step of execution along arbitrary code will be associated with a stack of environments--the current environment, the environment the current function was called from, etc. The operator <<- attempts to assign a value to the nearest object found in this environment hierarchy, and if none is found, assign it within the global environment. For example, below is a rudimentary adder.
f <- (function() { x <- 0; function(y) { x <<- x + y; x } })()
f(10) # 10
f(5) # 15
The function f has an environment which has a parent environment which has x . Using <<- , we can access that x , whereas if we had <- , the result would have been y every time instead of keeping track of the sum. The reason for this is that <- would have created a copy of x in the local scope, and it would always be 0 since the value was copied from the parent environment.
For further information about these intricacies, you can also look at the relevant R documentation.
链接地址: http://www.djcxy.com/p/73842.html上一篇: “x”和“x”,x <
下一篇: 在R中声明对象的不同方式
