RSS

Monthly Archives: August 2013

Variable Scope


Scope of variables in R is limited to the scope or functions in which variable is defined. R does not provide the facility of passing variable by reference. R uses stack to pass variables across different functions. Even it copy the global variable within the function and all the changes persist within that function.

Suppose, we have a R file, namely scope.R

vec = 11:20
Slave <- function(par1, par2, par3) {
par1 = 1
par2 = 2
vec[2] = -11
rm(par3)
print(“Slave Variables :”)
print(par1)
print(par2)
#Return error as this variable has been removed from the memory.
#print(par3)
print(vec)
}

Master <- function() {
par1=10
par2=20
par3=1:10
Slave(par1, par2, par3)
print(“Master Variables :”)
print(par1)
print(par2)
print(par3)
print(“Global vector remains same despite its 2nd element was changed by Salve funtion”)
print(vec)
}

Master()

Output of the above file: –

[1] “Slave Variables :”
[1] 1
[1] 2
[1]  11 -11  13  14  15  16  17  18  19  20
[1] “Master Variables :”
[1] 10
[1] 20
[1]  1  2  3  4  5  6  7  8  9 10
[1] “Global vector remains same despite its 2nd element was changed by Salve funtion”
[1] 11 12 13 14 15 16 17 18 19 20

R also has “oo” library for object oriented programming but oo is not available for R 3.0.1

 
Leave a comment

Posted by on August 29, 2013 in Variable Scope

 

Tags: , ,