R 中的全局和局部变量 [英] Global and local variables in R
问题描述
我是 R 的新手,我对 R 中局部和全局变量的使用感到很困惑.
I am a newbie for R, and I am quite confused with the usage of local and global variables in R.
我在互联网上读了一些帖子,说如果我使用 =
或 <-
我将在当前环境中分配变量,并使用 <<-
我可以在函数内部访问全局变量.
I read some posts on the internet that say if I use =
or <-
I will assign the variable in the current environment, and with <<-
I can access a global variable when inside a function.
但是,我记得在 C++ 中,每当您在方括号 {}
内声明变量时都会出现局部变量,所以我想知道这对 R 是否相同?或者只是为了 R 中的函数,我们有局部变量的概念.
However, as I remember in C++ local variables arise whenever you declare a variable inside brackets {}
, so I'm wondering if this is the same for R? Or is it just for functions in R that we have the concept of local variables.
我做了一个小实验,似乎表明只有括号是不够的,我有什么问题吗?
I did a little experiment, which seems to suggest that only brackets are not enough, am I getting anything wrong?
{
x=matrix(1:10,2,5)
}
print(x[2,2])
[1] 4
推荐答案
在函数内部声明的变量是该函数的局部变量.例如:
Variables declared inside a function are local to that function. For instance:
foo <- function() {
bar <- 1
}
foo()
bar
给出以下错误:Error: object 'bar' not found
.
如果你想让 bar
成为一个全局变量,你应该这样做:
If you want to make bar
a global variable, you should do:
foo <- function() {
bar <<- 1
}
foo()
bar
在这种情况下,bar
可以从函数外部访问.
In this case bar
is accessible from outside the function.
然而,与 C、C++ 或许多其他语言不同,括号不能确定变量的范围.例如,在以下代码片段中:
However, unlike C, C++ or many other languages, brackets do not determine the scope of variables. For instance, in the following code snippet:
if (x > 10) {
y <- 0
}
else {
y <- 1
}
y
在 if-else
语句之后仍然可以访问.
y
remains accessible after the if-else
statement.
正如您所说,您还可以创建嵌套环境.您可以查看这两个链接以了解如何使用它们:
As you well say, you can also create nested environments. You can have a look at these two links for understanding how to use them:
- http://stat.ethz.ch/R-manual/R-devel/library/base/html/environment.html
- http://stat.ethz.ch/R-manual/R-devel/library/base/html/get.html
这里有一个小例子:
test.env <- new.env()
assign('var', 100, envir=test.env)
# or simply
test.env$var <- 100
get('var') # var cannot be found since it is not defined in this environment
get('var', envir=test.env) # now it can be found
这篇关于R 中的全局和局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!