+1 vote
2 views
in R Programming by (3.4k points)
edited by
I want to set some global variables inside a function, how can I do that?

2 Answers

0 votes
by (26.9k points)

Let's first understand what Global Variables really are. Global Variables are the variables that remain throughout the execution of the program and can be accessed or changed from any part of the program. However, they also have a dependency on the perspective of a function.

You can set a global variable inside a function by using assign :

q <- "old"
test <- function () {
   assign("q", "new", envir = .GlobalEnv)
}
test()
q  # display the new value

or use <<- operator, but assign is preferred:

q <<- "new"

use them inside the function. 

Hope this helps, Cheers...!!

0 votes
by (50k points)

Inside a function the variables declared are local to that function. 

For e.g.:

foo <- function() {

    m <- 2

}

foo()

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

To make m a global variable, you can use the below code:

foo <- function() {

    m <<- 2

}

foo()

//In this case m is accessible from outside the function.

...