assign()和<< - 在R中有什么区别? [英] What is the difference between assign() and <<- in R?
问题描述
包含< - function(x){
x_squared < - x ^ 2
return( x_squared)
}
在这种情况下,从函数输入计算出的值是回。但是变量 x_squared
不可用。
但是如果你需要违反这个基本的函数编程原则'不知道R是多么严重的问题),并从函数返回一个对象,你有两个选择。
escape < - 功能(X){
x_squared<< - X ^ 2
分配( x_times_x,X * X,ENVIR = .GlobalEnv)
}
对象 x_squared
和 x_times_x
被返回。是一种方法比另一种更好,为什么这样?
.gmane.org / gmane.comp.lang.r.general / 227066rel =noreferrer>在一篇精彩的文章中r-help有一天。 << -
是关于封闭的环境,所以你可以做这样的事情(再次,我引用他的帖子从4月22日):
make.accumulator< -function(){
A< - 0
函数(X){
A<< - 一个+ X
A
}
}
> f< -make.accumulator()
> f(1)
[1] 1
> f(1)
[1] 2
> f(11)
[1] 13
> f(11)
[1] 24
这是<< -
作为词法范围的超级赋值。而不是简单地在全球环境中进行分配。为此,Thomas有这些选择的话:
恶意和错误的用法是修改全局环境中的
变量。 / p>
非常好的建议。
The normal approach to writing functions in R (as I understand) is to avoid side-effects and return a value from a function.
contained <- function(x) {
x_squared <- x^2
return(x_squared)
}
In this case, the value computed from the input into the function is returned. But the variable x_squared
is not available.
But if you need to violate this basic functional programming tenet (and I'm not sure how serious R is about this issue) and return an object from a function, you have two choices.
escape <- function(x){
x_squared <<- x^2
assign("x_times_x", x*x, envir = .GlobalEnv)
}
Both objects x_squared
and x_times_x
are returned. Is one method preferable to the other and why so?
Thomas Lumley answers this in a superb post on r-help the other day. <<-
is about the enclosing environment so you can do thing like this (and again, I quote his post from April 22 in this thread):
make.accumulator<-function(){
a <- 0
function(x) {
a <<- a + x
a
}
}
> f<-make.accumulator()
> f(1)
[1] 1
> f(1)
[1] 2
> f(11)
[1] 13
> f(11)
[1] 24
This is a legitimate use of <<-
as "super-assignment" with lexical scope. And not simply to assign in the global environment. For that, Thomas has these choice words:
The Evil and Wrong use is to modify variables in the global environment.
Very good advice.
这篇关于assign()和<< - 在R中有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!