Operators and Variables in R Language

Last updated on Dec 14 2021
R Deskmukh

Table of Contents

Operators and Variables in R Language

A variable provides us with named storage that our programs can manipulate. A variable in R can store an atomic vector, group of atomic vectors or a combination of many R objects. A valid variable name consists of letters, numbers and the dot or underline characters. The variable name starts with a letter or the dot not followed by a number.

Variable Name Validity Reason
var_name2. valid Has letters, numbers, dot and underscore
var_name% Invalid Has the character ‘%’. Only dot(.) and underscore allowed.
2var_name invalid Starts with a number
.var_name,

var.name

valid Can start with a dot(.) but the dot(.)should not be followed by a number.
.2var_name invalid The starting dot is followed by a number making it invalid.
_var_name invalid Starts with _ which is not valid

Variable Assignment

The variables can be assigned values using leftward, rightward and equal to operator. The values of the variables can be printed using print() or cat() function. The cat() function combines multiple items into a continuous print output.

# Assignment using equal operator.
var.1 = c(0,1,2,3)

# Assignment using leftward operator.
var.2 <- c("learn","R")

# Assignment using rightward operator. 
c(TRUE,1) -> var.3

print(var.1)
cat ("var.1 is ", var.1 ,"\n")
cat ("var.2 is ", var.2 ,"\n")
cat ("var.3 is ", var.3 ,"\n")
When we execute the above code, it produces the following result −
[1] 0 1 2 3
var.1 is 0 1 2 3 
var.2 is learn R 
var.3 is 1 1

Note − The vector c(TRUE,1) has a mix of logical and numeric class. So logical class is coerced to numeric class making TRUE as 1.

Data Type of a Variable

In R, a variable itself is not declared of any data type, rather it gets the data type of the R – object assigned to it. So R is called a dynamically typed language, which means that we can change a variable’s data type of the same variable again and again when using it in a program.

var_x <- "Hello"
cat("The class of var_x is ",class(var_x),"\n")

var_x <- 34.5
cat(" Now the class of var_x is ",class(var_x),"\n")

var_x <- 27L
cat(" Next the class of var_x becomes ",class(var_x),"\n")

When we execute the above code, it produces the following result −
The class of var_x is character
Now the class of var_x is numeric
Next the class of var_x becomes integer

Finding Variables

To know all the variables currently available in the workspace we use the ls() function. Also the ls() function can use patterns to match the variable names.

print(ls())
When we execute the above code, it produces the following result −
[1] “my var” “my_new_var” “my_var” “var.1”
[5] “var.2” “var.3” “var.name” “var_name2.”
[9] “var_x” “varname”
Note − It is a sample output depending on what variables are declared in your environment.
The ls() function can use patterns to match the variable names.

# List the variables starting with the pattern “var”.
print(ls(pattern = “var”))
When we execute the above code, it produces the following result −
[1] “my var” “my_new_var” “my_var” “var.1”
[5] “var.2” “var.3” “var.name” “var_name2.”
[9] “var_x” “varname”
The variables starting with dot(.) are hidden, they can be listed using “all.names = TRUE” argument to ls() function.

print(ls(all.name = TRUE))
When we execute the above code, it produces the following result −
[1] “.cars” “.Random.seed” “.var_name” “.varname” “.varname2”
[6] “my var” “my_new_var” “my_var” “var.1” “var.2”
[11]”var.3″ “var.name” “var_name2.” “var_x”

Deleting Variables

Variables can be deleted by using the rm() function. Below we delete the variable var.3. On printing the value of the variable error is thrown.

rm(var.3)
print(var.3)
When we execute the above code, it produces the following result −
[1] “var.3”
Error in print(var.3) : object ‘var.3’ not found
All the variables can be deleted by using the rm() and ls() function together.

rm(list = ls())
print(ls())
When we execute the above code, it produces the following result −
character(0)

R – Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. R language is rich in built-in operators and provides following types of operators.

Types of Operators

We have the following types of operators in R programming −
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Assignment Operators
• Miscellaneous Operators

Arithmetic Operators

Following table shows the arithmetic operators supported by R language. The operators act on each element of the vector.

Operator Description Example
+ Adds two vectors  

v <- c( 2,5.5,6)

t <- c(8, 3, 4)

print(v+t)

it produces the following result −

[1] 10.0  8.5  10.0

Subtracts second vector from the first  

v <- c( 2,5.5,6)

t <- c(8, 3, 4)

print(v-t)

it produces the following result −

[1] -6.0  2.5  2.0

* Multiplies both vectors  

v <- c( 2,5.5,6)

t <- c(8, 3, 4)

print(v*t)

it produces the following result −

[1] 16.0 16.5 24.0

/ Divide the first vector with the second  

v <- c( 2,5.5,6)

t <- c(8, 3, 4)

print(v/t)

When we execute the above code, it produces the following result −

[1] 0.250000 1.833333 1.500000

%% Give the remainder of the first vector with the second  

v <- c( 2,5.5,6)

t <- c(8, 3, 4)

print(v%%t)

it produces the following result −

[1] 2.0 2.5 2.0

%/% The result of division of first vector with second (quotient)  

v <- c( 2,5.5,6)

t <- c(8, 3, 4)

print(v%/%t)

it produces the following result −

[1] 0 1 1

^ The first vector raised to the exponent of second vector  

v <- c( 2,5.5,6)

t <- c(8, 3, 4)

print(v^t)

it produces the following result −

[1]  256.000  166.375 1296.000

Relational Operators

Following table shows the relational operators supported by R language. Each element of the first vector is compared with the corresponding element of the second vector. The result of comparison is a Boolean value.

Operator Description Example
> Checks if each element of the first vector is greater than the corresponding element of the second vector.  

v <- c(2,5.5,6,9)

t <- c(8,2.5,14,9)

print(v>t)

it produces the following result −

[1] FALSE  TRUE FALSE FALSE

< Checks if each element of the first vector is less than the corresponding element of the second vector.  

v <- c(2,5.5,6,9)

t <- c(8,2.5,14,9)

print(v < t)

it produces the following result −

[1]  TRUE FALSE  TRUE FALSE

== Checks if each element of the first vector is equal to the corresponding element of the second vector.  

v <- c(2,5.5,6,9)

t <- c(8,2.5,14,9)

print(v == t)

it produces the following result −

[1] FALSE FALSE FALSE  TRUE

<= Checks if each element of the first vector is less than or equal to the corresponding element of the second vector.  

v <- c(2,5.5,6,9)

t <- c(8,2.5,14,9)

print(v<=t)

it produces the following result −

[1]  TRUE FALSE  TRUE  TRUE

>= Checks if each element of the first vector is greater than or equal to the corresponding element of the second vector.  

v <- c(2,5.5,6,9)

t <- c(8,2.5,14,9)

print(v>=t)

it produces the following result −

[1] FALSE  TRUE FALSE  TRUE

!= Checks if each element of the first vector is unequal to the corresponding element of the second vector.  

v <- c(2,5.5,6,9)

t <- c(8,2.5,14,9)

print(v!=t)

it produces the following result −

[1]  TRUE  TRUE  TRUE FALSE

Logical Operators

Following table shows the logical operators supported by R language. It is applicable only to vectors of type logical, numeric or complex. All numbers greater than 1 are considered as logical value TRUE.
Each element of the first vector is compared with the corresponding element of the second vector. The result of comparison is a Boolean value.

Operator Description Example
& It is called Element-wise Logical AND operator. It combines each element of the first vector with the corresponding element of the second vector and gives a output TRUE if both the elements are TRUE.  

v <- c(3,1,TRUE,2+3i)

t <- c(4,1,FALSE,2+3i)

print(v&t)

it produces the following result −

[1]  TRUE  TRUE FALSE  TRUE

| It is called Element-wise Logical OR operator. It combines each element of the first vector with the corresponding element of the second vector and gives a output TRUE if one the elements is TRUE.  

v <- c(3,0,TRUE,2+2i)

t <- c(4,0,FALSE,2+3i)

print(v|t)

it produces the following result −

[1]  TRUE FALSE  TRUE  TRUE

! It is called Logical NOT operator. Takes each element of the vector and gives the opposite logical value.  

v <- c(3,0,TRUE,2+2i)

print(!v)

it produces the following result −

[1] FALSE  TRUE FALSE FALSE

The logical operator && and || considers only the first element of the vectors and give a vector of single element as output.

Operator Description Example
&& Called Logical AND operator. Takes first element of both the vectors and gives the TRUE only if both are TRUE.  

v <- c(3,0,TRUE,2+2i)

t <- c(1,3,TRUE,2+3i)

print(v&&t)

it produces the following result −

[1] TRUE

|| Called Logical OR operator. Takes first element of both the vectors and gives the TRUE if one of them is TRUE.  

v <- c(0,0,TRUE,2+2i)

t <- c(0,3,TRUE,2+3i)

print(v||t)

it produces the following result −

[1] FALSE

Assignment Operators

These operators are used to assign values to vectors.

Operator Description Example
<−

or

=

or

<<−

Called Left Assignment  

v1 <- c(3,1,TRUE,2+3i)

v2 <<- c(3,1,TRUE,2+3i)

v3 = c(3,1,TRUE,2+3i)

print(v1)

print(v2)

print(v3)

it produces the following result −

[1] 3+0i 1+0i 1+0i 2+3i

[1] 3+0i 1+0i 1+0i 2+3i

[1] 3+0i 1+0i 1+0i 2+3i

->

or

->>

Called Right Assignment  

c(3,1,TRUE,2+3i) -> v1

c(3,1,TRUE,2+3i) ->> v2

print(v1)

print(v2)

it produces the following result −

[1] 3+0i 1+0i 1+0i 2+3i

[1] 3+0i 1+0i 1+0i 2+3i

Miscellaneous Operators

These operators are used to for specific purpose and not general mathematical or logical computation.

Operator Description Example
: Colon operator. It creates the series of numbers in sequence for a vector.  

v <- 2:8

print(v)

it produces the following result −

[1] 2 3 4 5 6 7 8

%in% This operator is used to identify if an element belongs to a vector.  

v1 <- 8

v2 <- 12

t <- 1:10

print(v1 %in% t)

print(v2 %in% t)

it produces the following result −

[1] TRUE

[1] FALSE

%*% This operator is used to multiply a matrix with its transpose.  

M = matrix( c(2,6,5,1,10,4), nrow = 2,ncol = 3,byrow = TRUE)

t = M %*% t(M)

print(t)

it produces the following result −

[,1] [,2]

[1,]   65   82

[2,]   82  117

So, this brings us to the end of blog. This Tecklearn ‘Operators and Variables in R Language’ blog helps you with commonly asked questions if you are looking out for a job in Data Science. If you wish to learn R Language and build a career in Data Science domain, then check out our interactive, Data Science using R Language Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

https://www.tecklearn.com/course/data-science-training-using-r-language/

Data Science using R Language Training

About the Course

Tecklearn’s Data Science using R Language Training develops knowledge and skills to visualize, transform, and model data in R language. It helps you to master the Data Science with R concepts such as data visualization, data manipulation, machine learning algorithms, charts, hypothesis testing, etc. through industry use cases, and real-time examples. Data Science course certification training lets you master data analysis, R statistical computing, connecting R with Hadoop framework, Machine Learning algorithms, time-series analysis, K-Means Clustering, Naïve Bayes, business analytics and more. This course will help you gain hands-on experience in deploying Recommender using R, Evaluation, Data Transformation etc.

Why Should you take Data Science Using R Training?

• The Average salary of a Data Scientist in R is $123k per annum – Glassdoor.com
• A recent market study shows that the Data Analytics Market is expected to grow at a CAGR of 30.08% from 2020 to 2023, which would equate to $77.6 billion.
• IBM, Amazon, Apple, Google, Facebook, Microsoft, Oracle & other MNCs worldwide are using data science for their Data analysis.

What you will Learn in this Course?

Introduction to Data Science
• Need for Data Science
• What is Data Science
• Life Cycle of Data Science
• Applications of Data Science
• Introduction to Big Data
• Introduction to Machine Learning
• Introduction to Deep Learning
• Introduction to R&R-Studio
• Project Based Data Science
Introduction to R
• Introduction to R
• Data Exploration
• Operators in R
• Inbuilt Functions in R
• Flow Control Statements & User Defined Functions
• Data Structures in R
Data Manipulation
• Need for Data Manipulation
• Introduction to dplyr package
• Select (), filter(), mutate(), sample_n(), sample_frac() & count() functions
• Getting summarized results with the summarise() function,
• Combining different functions with the pipe operator
• Implementing sql like operations with sqldf()
Visualization of Data
• Loading different types of datasets in R
• Arranging the data
• Plotting the graphs
Introduction to Statistics
• Types of Data
• Probability
• Correlation and Co-variance
• Hypothesis Testing
• Standardization and Normalization
Introduction to Machine Learning
• What is Machine Learning?
• Machine Learning Use-Cases
• Machine Learning Process Flow
• Machine Learning Categories
• Supervised Learning algorithm: Linear Regression and Logistic Regression
Logistic Regression
• Intro to Logistic Regression
• Simple Logistic Regression in R
• Multiple Logistic Regression in R
• Confusion Matrix
• ROC Curve
Classification Techniques
• What are classification and its use cases?
• What is Decision Tree?
• Algorithm for Decision Tree Induction
• Creating a Perfect Decision Tree
• Confusion Matrix
• What is Random Forest?
• What is Naive Bayes?
• Support Vector Machine: Classification
Decision Tree
• Decision Tree in R
• Information Gain
• Gini Index
• Pruning
Recommender Engines
• What is Association Rules & its use cases?
• What is Recommendation Engine & it’s working?
• Types of Recommendations
• User-Based Recommendation
• Item-Based Recommendation
• Difference: User-Based and Item-Based Recommendation
• Recommendation use cases
Time Series Analysis
• What is Time Series data?
• Time Series variables
• Different components of Time Series data
• Visualize the data to identify Time Series Components
• Implement ARIMA model for forecasting
• Exponential smoothing models
• Identifying different time series scenario based on which different Exponential Smoothing model can be applied
Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "Operators and Variables in R Language"

Leave a Message

Your email address will not be published. Required fields are marked *