Monday, May 7, 2018

R: Scope of variables within user defined functions



R: Scope of variables within user defined functions


Source: https://stackoverflow.com/questions/10904124/global-and-local-variables-in-r

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.



No comments:

Post a Comment