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

1 Answer

0 votes
by (6.1k 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...!!

...