Global and local variables in R

r

Solution

Variables declared inside a function are local to that function. For instance:

foo <- function() {
    bar <- 1
}
foo()
bar

gives the following error: `Error: object 'bar' not found`.

If you want to make `bar` a global variable, you should do:

foo <- function() {
    bar <<- 1
}
foo()
bar

In this case `bar` is accessible from outside the function.

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` 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

Here you have a small example:

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

Problem

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. 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 ```

Original source