How To Define Variables And Constants In R


In this article, I am going to explain about variables and constants in R. I will demonstrate how to define variables, declare variables and how to define constants and use predefined constants in R language.

Variables in R

In R, we can store data in a memory location and these memory locations have a name: They're called variables. Each and every variable in R can have different name which is referred to as an identifier and these identifiers can store values of different datatypes.

There are different ways to define a variable in R which are:

  • In R, a variable always starts with a letter or with a period. A variable if started with a dot cannot be succeeded by a number.
  • Variables cannot be created with keywords which are already predefined in R; that is keywords which are reserved, as their names or identifiers.
  • A variable in R can be defined using just letters or an underscore with letters, dots along with letters. We can even define variables as a mixture of digits, dot, underscore and letters.

In R, a few instances of names of variables that are relevant are name, Var, var_1, .var, var.1

In R, a few instances of names of variables which are irrelevant are 5var, var@a, _sub, FALSE, .2ab.

From the above example, we can see that in R, to define a variable as a legitimate name of a memory location, we can use underscore at the beginning of the variable name or dot can also be used to separate letters from numbers in variable name. Various examples can be considered such as var.1, var.a, var_1.

Assigning values to variables

In R, assigning values to a variable can be specified or achieved using the syntax of left angular brackets signifying the syntax of an arrow. After assigning values to a variable, these values can be printed using the predefined cat() function and print() function. To integrate multiple statements assigned to a single variable and separated by double quotation marks and commas, we can use function of cat().

Consider the example given below,

> a = c(1,4,3,2)  
> b.6 <- c("Defining functions in","R Language")  
> x_y <- 34  
> a  
[1] 1 4 3 2  
> b.6  
[1] "Defining functions in" "R Language"                     
> x_y  
[1] 34  

Therefore variable assignment can be done using any of the syntaxes discussed above to assign a variable with a value of different datatypes.

Different datatypes of variables

Once we declare a variable in R to be of a particular datatype and run the command on R console to get the output of variable, then the same variable can be assigned over and over again with a different value having a different datatype. This shows the dynamic nature of R programming language.

Consider the following example,

> a <- ' Greetings'  
> cat("Variable a has a class ",class(a),"\n")  
Variable a has a class character   
> x <- 12  
> cat("Variable x has a class ",class(a),"\n")  
 Variable x has a class numeric  
> name <- 'Sam Hopkins'  
> cat("Variable name has a class ",class(name),"\n")  
Variable name has a class character 

Displaying variables in directory

Through the function ls(), the name of all the functions and variables or we can say objects defined within a particular workspace can be obtained in detail. In order to extract a particular from workspace, pattern matching attribute can be used to list the details of the exact variable from a workspace in R.

The concept is demonstrated as follows,

> num_var1 <- 40.5  
> num_var2 <- 71  
> obj_datatype <- c("vector", "matrix", "factor")  
> ls()
[1] "num_var1" "num_var2" "obj_datatype"   

structure function in ls

in ls.str() function, str() is a separate function which gives more detail about variables rather than just names of the variables.

> ls.str()  
name :  chr "Elijah Hopkins"  
num_var1 :  num 40.5  
num_var2 :  num 71  
obj_datatype :  chr [1:3] "vector" "matrix" "factor"  
x :  num 12  

From the code snippet created above, it can be said that all the variables that were defined in a workspace can be listed using the ls() function.

Removing directory variables

If there are unwanted variables along with functins defined in R console directory, then we can remove and delete definition of such unnecessary variables through rm() function. For example, if we want to remove a variable named “x” defined in R console directory, then we can mention or include the name of that variable inside the function rm() as argument of a function.

Following code snippet explains rm() function,

> x<- 12  
> ls.str()  
x :  num 12  
> rm(x)  
> x  
Error: object 'x' not found  

To delete the whole directory in one go, we can use an argument called list inside rm() function as follows rm(list = ls()). The list contains the names of variables in the form of a vector which need to be deleted.

Let us take a look at the below code snippet,

> rm(list = ls())  
> ls()  

From the above code snippet, we can see that all the variables inside the directory have been deleted.

Defining constants in R

In R, we can also generate different types of constants such as numeric and character constants.

Numerical type constants

Numerical constants comprise all kinds of numbers such as integer and double. We can confirm the datatype of numbers using typeof() function.

Here are some examples,

> typeof(5)  
[1] "double"  
> typeof(4L)  
[1] "integer"  
> typeof(3i)  
[1] "complex"  

Character type constants

We can also generate constants of datatype character with the help of single and double quotation marks. We can demonstrate that using the below code snippet,

> 'student'  
[1] "student"  
> typeof("7")  
[1] "character"  

Predefined Constants

Predefined constants are also available in R. The values of these constants are demonstrated as follows,

> print(LETTERS)   
 [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z"  
> print(pi)  
[1] 3.141593  
> print(  
 [1] "January"   "February"  "March"     "April"     "May"       "June"      "July"      "August"    "September" "October"   "November"  "December"   

Getting input from user

In R, user data can also be provided as input to R console using the readline() function. The data read by the function can be stored in a variable later. Getting user input can be demonstrated as follows,

> > My_name <- readline(prompt="Enter your name: ")  
Enter first name: abhishek  
> My_age <- readline(prompt="Enter age: ")  
Enter your age: 25  
> My_age <- as.integer(My_age)  
> print(paste("Hello,"my name is”, name, "and I am", age+1, "years old."))  
[1] "Hi, abhishek next year you will be 25 years old.">  


In this article, I explained about variables and constants in R. I also demonstrated how to define variables, declare variables and how to define constants and use predefined constants in R language. Proper coding snippets and output screenshots are also provided. 

Similar Articles