The Wayback Machine - https://web.archive.org/web/20240913213341/https://www.geeksforgeeks.org/scope-of-variable-in-r/
Open In App

Scope of Variable in R

Last Updated : 04 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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




# R program to demonstrate
# variable assignment
 
# Assignment using equal operator
var1 = c(0, 1, 2, 3)
print(var1)
 
# Assignment using leftward operator
var2 <- c("Python", "R")
print(var2)
 
# A Vector Assignment
a = c(1, 2, 3, 4)
print(a)
b = c("Debi", "Sandeep", "Subham", "Shiba")
print(b)
 
# A group of vectors Assignment using list
c = 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"

Time Complexity: O(1)
Auxiliary Space: O(1)

Naming convention for Variables

  • 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




# R program to demonstrate
# rules for naming the variables
 
# Correct naming
b2 = 7
 
# Correct naming
Amiya_Profession = "Student"
 
# Correct naming
Amiya.Profession = "Student"
 
# Wrong naming
2b = 7
 
# Wrong naming
Amiya@Profession = "Student"


Above code when executed will generate an error because of the wrong naming of variables.

Error: unexpected symbol in "2b"
Execution halted

Scope of a variable

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.

Global Variable

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.

Python3




# 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

Time Complexity: O(1)
Auxiliary Space: O(1)

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.

Local Variable

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




# 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)


Time Complexity: O(1)
Auxiliary Space: O(1)

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




# 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

Time Complexity: O(1)
Auxiliary Space: O(1)

Accessing Global Variables

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: 

R




f = function() {
# a is a local variable here
a <-1
}
f()
 
# Can't access outside the function
print(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




# 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 function
print(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().



Previous Article
Next Article

Similar Reads

Scope of the R Programming Language in India
In India, the scope of the R programming language is expanding, particularly in fields that rely heavily on data analysis, such as finance, pharmaceuticals, research, and technology. With the growing importance of big data and analytics in the business landscape, R's powerful statistical capabilities and data visualization tools make it a valuable
3 min read
How to Create or Modify a Variable in SAS Programming?
This will help you to create or modify a variable. It is common to define a new variable based on the existing variable. Let's create a dataset In the code below, we are creating a dataset named as Example1 which is going to store on WORK(temporary) library. In this dataset, there would be a variable called OldRate which contains a numeric value. T
2 min read
Rank variable by group using Dplyr package in R
In this article, we are going to see how to rank the variable by group using dplyr in R Programming Language. The dplyr package in R is used to perform mutations and data manipulations in R. It is particularly useful for working with data frames and data tables. The package can be downloaded and installed into the working directory using the follow
2 min read
How to Assign Colors to Categorical Variable in ggplot2 Plot in R ?
In this article, we will see how to assign colors to categorical Variables in the ggplot2 plot in R Programming language. Note: Here we are using a scatter plot, the same can be applied to any other graph. Dataset in use: YearPointsUsers1201130user12201220user23201315user34201435user45201550user5 To Create an R plot, we use ggplot() function and to
2 min read
Variable importance plot using random forest package in R
As the name indicates Variable Importance Plot is a which used random forest package to plot the graph based on their accuracy and Gini Coefficient. If the accuracy of the variable is high then it's going to classify data accurately and Gini Coefficient is measured in terms of the homogeneity of nodes in a random forest. And the Mean Decrease Accur
2 min read
Dplyr - Groupby on multiple columns using variable names in R
The group_by() method is used to group the data contained in the data frame based on the columns specified as arguments to the function call. The group_by() function takes as an argument, the across and all of the methods which has to be applied on the specified grouping over all the columns of the data frame. Syntax: group_by(col1, col2,..) This i
2 min read
Multiple Density Plots and Coloring by Variable with ggplot2 in R
In this article, we will discuss how to make multiple density plots with coloring by variable in R Programming Language. To make multiple density plots with coloring by variable in R with ggplot2, we first make a data frame with values and categories. Then we draw the ggplot2 density plot using the geom_desnity() function. To color them according t
3 min read
Create a ranking variable with Dplyr package in R
In this article, we will discuss how to create a ranking variable with the Dplyr package in R. Installation To install this package type the below command in the terminal. install.packages("dplyr") The mutate method can be used to rearrange data into a different orientation by performing various aggregate and statistic method and assigning it to ne
3 min read
How to Add Vertical Lines By a Variable in Multiple Density Plots with ggplot2 in R
In this article, we will discuss how to add vertical lines by a variable in multiple density plots with ggplot2 package in the R Programming language. To do so first we will create multiple density plots colored by group and then add the line as a separate element. Basic Multiple Density Plot: To make multiple density plots with coloring by variabl
3 min read
How to Create Added Variable Plots in R?
In this article, we will discuss how to create an added variable plot in the R Programming Language. The Added variable plot is an individual plot that displays the relationship between a response variable and one predictor variable in a multiple linear regression model while controlling for the presence of other predictor variables in the model. I
3 min read
How To Annotate Clusters with Circle/Ellipse by a Variable in R ggplot2
In this article, we will discuss how to annotate Clusters with Circle/Ellipse by a categorical variable in the R Programming Language using the ggplot2 package. To add a circle or ellipse around a cluster of data points, we use the geom_mark_circle() and geom_mark_ellipse() function of the ggforce package. This function automatically computes the c
5 min read
Plot Only One Variable in ggplot2 Plot in R
In this article, we will be looking at the two different methods to plot only one variable in the ggplot2 plot in the R programming language. Draw ggplot2 Plot Based On Only One Variable Using ggplot &amp; nrow Functions In this approach to drawing a ggplot2 plot based on the only one variable, firstly the user needs to install and import the ggplo
5 min read
Get Column Index in Data Frame by Variable Name in R
R is an open-source programming language that is used as a statistical software and data analysis tool. In R Programming Language we can work on specific columns based on their names. In this article, we will learn different methods to extract the Get Column Index in Data Frame by Variable Name in R Extract Column Index of Variable with Exact Match
5 min read
How to Print String and Variable on Same Line in R
Printing a string and a variable on the same line is useful for improving readability, concatenating dynamic output, aiding in debugging by displaying variable values, and formatting output for reports or user display. Below are different approaches to printing String and Variable on the Same Line using R Programming Language. Table of ContentUsing
3 min read
How do you create a factor variable in R
In R programming Language factor variables are a fundamental data type for categorical data. Factor variables, unlike numeric or character variables, reflect defined categories, making them useful for a variety of statistical analysis and data modeling applications. What are factor variables?Factor variables in R represent categorical data, such as
3 min read
How to Change value of variable with dplyr
The Dplyr package in R is a powerful tool for data manipulation and transformation. It provides a set of functions that allow you to perform common data manipulation tasks concisely and efficiently. One of these tasks is changing the value of a variable within a data frame. This article will guide you through various methods to change the value of
4 min read
Variable Selection Techniques In R
Variable selection, also known as feature selection, is the process of identifying and choosing the most important predictors for a model. In R Programming Language This process leads to simpler, faster, and more interpretable models, and helps in preventing overfitting. Overfitting occurs when a model is too complex and captures noise in the data
4 min read
How to use a variable in dplyr::filter?
Data manipulation and transformation require the use of data manipulation verbs and the dplyr package in R is crucial. One of its functions is filter(), which allows the row to be selected based on imposed conditions. However, one of the activities that frequently occur in data analysis processing is data filtering based on a variable with changing
4 min read
Supplementary Qualitative Variable Labels in FactoMinR
The FactoMineR is a powerful R package designed for multivariate data analysis including the Principal Component Analysis (PCA), Correspondence Analysis (CA), and Multiple Correspondence Analysis (MCA). One of the key features of FactoMineR is the ability to handle supplementary variables. This article will focus on how to handle supplementary qual
4 min read
How to Create a Lag Variable Within Each Group in R?
Creating lag variables within groups is a common task in time series and panel data analysis. It involves generating a new variable that contains the value of an existing variable from a previous period or row within each group. This process is crucial for tasks such as time series forecasting, panel data analysis, and feature engineering in machin
5 min read
What are the restrictions on variable naming in R Programming Language
In R programming, variable names must adhere to specific rules and restrictions to ensure that they are valid and do not conflict with reserved keywords or functions. The main restrictions on variable naming in R include not starting with a number, avoiding reserved keywords, and ensuring that names are case-sensitive. Following these guidelines is
2 min read
How to Choose Variable to Display in Tooltip When Using ggplotly in R
Interactive visualizations are a powerful way to explore and present data and plotly are one of R's most popular libraries for creating these interactive plots. When combined plotly with ggplot2 using ggplotly, you can convert static ggplot2 plots into interactive ones. One key feature ggplotly is the ability to display tooltips, which provide addi
3 min read
How to display a variable with subscript ggplot2 graph in R?
In R, the ggplot2 package is one of the most popular and powerful tools for creating visually appealing and customizable plots. Sometimes, you may need to display mathematical notation or subscripts in your graphs, especially when working with scientific data or equations. This article will guide you through the process of displaying a variable wit
4 min read
How to Display Average Line for Y Variable Using ggplot2 in R
In this article, we will explore how to display the average line for a Y variable using ggplot2. Adding an average line is useful in understanding the central tendency of data and making comparisons across different groups. Introduction to ggplot2 in RThe ggplot2 package is one of the most widely used packages for data visualization in R. It provid
4 min read
Coloring Points Based on Variable with R ggpairs
This article will explain how to color points based on a variable using ggpairs() By adding color to the points in a pairwise plot based on a categorical or continuous variable, we can easily see how different categories or ranges of values behave across multiple pairwise relationships using R Programming Language. ggpairs() function in RThe ggpair
3 min read
How to Display Central Limit Theorem Using Uniform Random Variable in R
In this article, we will explain the Central Limit Theorem using a uniform distribution in R and visualize the results to confirm the theorem's behavior. Introduction to Central Limit Theorem (CLT)The Central Limit Theorem (CLT) is one of the most fundamental concepts in probability and statistics. It states that, for a sufficiently large sample si
5 min read
Introduction of Object Oriented Programming
As the name suggests, Object-Oriented Programming or OOPs refers to languages that use objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of
6 min read
Features of C Programming Language
C is a procedural programming language. It was initially developed by Dennis Ritchie in the year 1972. It was mainly developed as a system programming language to write an operating system. The main features of C language include low-level access to memory, a simple set of keywords, and a clean style, these features make C language suitable for sys
3 min read
Differences between Procedural and Object Oriented Programming
This article focuses on discussing the differences between procedural and object-oriented programming. Procedural Programming Procedural Programming can be defined as a programming model which is derived from structured programming, based upon the concept of calling procedure. Procedures, also known as routines, subroutines or functions, simply con
2 min read
type() function in Python
The type() function is mostly used for debugging purposes. Two different types of arguments can be passed to type() function, single and three arguments. If a single argument type(obj) is passed, it returns the type of the given object. If three argument types (object, bases, dict) are passed, it returns a new type object. Python type() function Sy
5 min read