Global variables in R.

733    Asked by Vishaltiwari in Data Science , Asked on Jul 14, 2021

I want to set some global variables inside a function, how can I do that? What are Global variables?


Answered by Ota Azuma

Variables that are created outside of a function are known as global variables. Global variables can be used by everyone, both inside of functions and outside.

R Global Variables

Create a variable outside of a function and use it inside the function: ...

Create a variable inside of a function with the same name as the global variable: ...

If you use the assignment operator <<- , the variable belongs to the global scope:

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



Your Answer

Interviews

Parent Categories