R Scope

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 –

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:-

Output:-

r_local_variable

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.

Recommended:-  R repeat Loop

Example:-

Output:-

r_accessing_global_variable

In this tutorial we have learn about the R Scope and its application with practical example. I hope you will like this tutorial.