Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
4 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 (46k 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 (106k 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.

Related questions

0 votes
2 answers
+1 vote
2 answers
0 votes
1 answer
asked Aug 5, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...