Scope of Variable in R

22 Apr, 2020
In R, variables are the containers for storing data values. They are reference, or pointers, to an object in memory which means that whenever a variable is assigned to an instance, it gets mapped to that instance. A variable in R can store a vector, a group of vectors or a combination of many R objects.
Example:
# R program to demonstrate # variable assignment    # Assignment using equal operatorvar1 = c(0, 1, 2, 3)print(var1)  # Assignment using leftward operatorvar2 <- c("Python", "R")print(var2)  # A Vector Assignmenta = c(1, 2, 3, 4)print(a)b = c("Debi", "Sandeep", "Subham", "Shiba")print(b)  # A group of vectors Assignment using listc = list(a, b)print(c)
Output:
[1] 0 1 2 3
[1] "Python" "R"     
[1] 1 2 3 4
[1] "Debi"    "Sandeep" "Subham"  "Shiba"  
[[1]]
[1] 1 2 3 4

[[2]]
[1] "Debi"    "Sandeep" "Subham"  "Shiba"  

The variable name in R has to be Alphanumeric characters with an exception of underscore(‘_’) and period(‘.’), the special characters which can be used in the variable names.
The variable name has to be started always with an alphabet.
Other special characters like(‘!’, ‘@’, ‘#’, ‘$’) are not allowed in the variable names.
Example:
# R program to demonstrate # rules for naming the variables   # Correct namingb2 = 7   # Correct namingAmiya_Profession = "Student"   # Correct namingAmiya.Profession = "Student"   # Wrong naming2b = 7   # Wrong namingAmiya@Profession = "Student" 
Above code when executed will generate an error because of the wrong naming of variables.
Error: unexpected symbol in "2b"
Execution halted

The location where we can find a variable and also access it if required is called the scope of a variable. There are mainly two types of variable scopes:
Global Variables: Global variables are those variables that exist throughout the execution of a program. It can be changed and accessed from any part of the program.
Local Variables: Local variables are those variables that exist only within a certain part of a program like a function and are released when the function call ends.
As the name suggests, Global Variables can be accessed from any part of the program.
They are available throughout the lifetime of a program.
They are declared anywhere in the program outside all of the functions or blocks.
Declaring global variables: Global variables are usually declared outside of all of the functions and blocks. They can be accessed from any portion of the program.
# R program to illustrate  # usage of global variables     # global variable global = 5    # global variable accessed from # within a function display = function(){  print(global)} display()   # changing value of global variable  global = 10 display()
Output:
[1] 5
[1] 10

In the above code, the variable ‘global‘ is declared at the top of the program outside all of the functions so it is a global variable and can be accessed or updated from anywhere in the program.
Variables defined within a function or block are said to be local to those functions.
Local variables do not exist outside the block in which they are declared, i.e. they can not be accessed or used outside that block.
Declaring local variables: Local variables are declared inside a block.
Example:
# R program to illustrate  # usage of local variables    func = function(){  # this variable is local to the   # function func() and cannot be    # accessed outside this function   age = 18    }   print(age)
Output:
Error in print(age) : object 'age' not found

The above program displays an error saying “object ‘age’ not found”. The variable age was declared within the function “func()” so it is local to that function and not visible to the portion of the program outside this function.
To correct the above error we have to display the value of variable age from the function “func()” only.
Example:
# R program to illustrate  # usage of local variables    func = function(){  # this variable is local to the   # function func() and cannot be    # accessed outside this function   age = 18      print(age)}   cat("Age is:\n")func()
Output:
Age is:
[1] 18

Global Variables can be accessed from anywhere in the code unlike local variables that have a scope restricted to the block of code in which they are created.
Example:
f = function() {   # a is a local variable here   a <-1}f()  # Can't access outside the functionprint(a) # This'll give error
Output:
Error in print(a) : object 'a' not found

In the above code, we see that we are unable to access variable “a” outside the function as it’s assigned by an assignment operator(<-) that makes “a” as a local variable. To make assignments to global variables, a super assignment operator(<<-) is used.
How super assignment operator works?When using this operator within a function, it searches for the variable in the parent environment frame, if not found it keeps on searching the next level until it reaches the global environment. If the variable is still not found, it is created and assigned at the global level.
Example:
# R program to illustrate# Scope of variables  outer_function = function(){  inner_function = function(){    # Note that "<<-" operator here    # makes a as global variable    a <<- 10    print(a)  }  inner_function()  print(a)}outer_function()  # Can access outside the functionprint(a)
Output:
[1] 10
[1] 10
[1] 10

When the statement “a <<- 10” is encountered within inner_function(), it looks for the variable “a” in the outer_function() environment. When the search fails, it searches in R_GlobalEnv. Since “a” is not defined in this global environment as well, it is created and assigned there which is now referenced and printed from within inner_function() as well as outer_function().
Picked
R-Variables
Programming Language
R Language
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.