In this tutorial you will learn about the R Scope and its application with practical example.
R Scope
Scope defines the region of visibility or availability for a variable, out of which we can not reference that variable. There are two main kinds of scope.
- global
- local
R Global Variable
Global variables can be accessed at any point throughout the program, and can be used in any function. There is single copy of the global variable is available. Global variables are defined outside of all the functions, usually on top of the program.
R Local Variable
Variable declared inside a function or block of code are called local variables. They can be accessed only inside that function or block of code. Local variables are not available outside the function.
Example:-
Let’s take a simple R program –
1 2 3 4 5 6 7 |
funA <- function(){ b <- 10 funB <- function(){ c <- 20 } } a <- 15 |
In the above example R program, for funB() both a and b are global variables. However, for funA(), b is a local variable and only a is global variable. The variable c is completely invisible to funA().
Note :- A program can have same name for local and global variables but local variable overrides the value.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
funA <- function(){ a <- 20 funB <- function(){ a <- 30 print(paste("Value of a inside funB is- ",a)) } funB() print(paste("Value of a inside funA is- ",a)) } print("W3Adda - R Local Variables") a <- 10 print(paste("Value of global a before function invoked- ",a)) funA() print(paste("Value of global a after function invoked- ",a)) |
Output:-
Accessing global variables
In R, super assignment operator “<<-” is used to refer variables from global environment, if we try to access a variable that does not exists then it is created and assigned at the global level.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
funA <- function(){ funB <- function(){ a <<- 30 print(paste("Value of a inside funB is- ",a)) } funB() print(paste("Value of a inside funA is- ",a)) } print("W3Adda - R Accessing Global Variables") a <- 10 print(paste("Value of global a before function invoked- ",a)) funA() print(paste("Value of global a after function invoked- ",a)) |
Output:-