The Wayback Machine - https://web.archive.org/web/20240828110659/https://www.geeksforgeeks.org/r-operators/
Open In App

R Operators

Last Updated : 26 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Operators are the symbols directing the compiler to perform various kinds of operations between the operands. Operators simulate the various mathematical, logical, and decision operations performed on a set of Complex Numbers, Integers, and Numericals as input operands. 

R Operators 

R supports majorly four kinds of binary operators between a set of operands. In this article, we will see various types of operators in R Programming language and their usage.

Arithmetic Operators

Arithmetic Operators modulo using the specified operator between operands, which may be either scalar values, complex numbers, or vectors. The R operators are performed element-wise at the corresponding positions of the vectors. 

Addition operator (+)

The values at the corresponding positions of both operands are added. Consider the following R operator snippet to add two vectors:

R
a <- c (1, 0.1)
b <- c (2.33, 4)
print (a+b)
 Output : 3.33  4.10 

Subtraction Operator (-)

The second operand values are subtracted from the first. Consider the following R operator snippet to subtract two variables:

R
 a <- 6
 b <- 8.4
 print (a-b)
Output : -2.4 

Multiplication Operator (*) 

The multiplication of corresponding elements of vectors and Integers are multiplied with the use of the ‘*’ operator.

R
B= c(4,4) 
C= c(5,5)
print (B*C)
Output : 20 20

Division Operator (/) 

The first operand is divided by the second operand with the use of the ‘/’ operator.

R
 a <- 10
 b <- 5
 print (a/b)
Output : 2

Power Operator (^)

The first operand is raised to the power of the second operand.

R
 a <- 4
 b <- 5
 print(a^b)
Output : 1024

Modulo Operator (%%)

The remainder of the first operand divided by the second operand is returned.

R
list1<- c(2, 22)
list2<-c(2,4)
print(list1 %% list2)
Output : 0  2

The following R code illustrates the usage of all Arithmetic R operators.

R
# R program to illustrate 
# the use of Arithmetic operators
vec1 <- c(0, 2)
vec2 <- c(2, 3)

# Performing operations on Operands
cat ("Addition of vectors :", vec1 + vec2, "\n")
cat ("Subtraction of vectors :", vec1 - vec2, "\n")
cat ("Multiplication of vectors :", vec1 * vec2, "\n")
cat ("Division of vectors :", vec1 / vec2, "\n")
cat ("Modulo of vectors :", vec1 %% vec2, "\n")
cat ("Power operator :", vec1 ^ vec2)

Output 

Addition of vectors : 2 5 
Subtraction of vectors : -2 -1 
Multiplication of vectors : 0 6 
Division of vectors : 0 0.6666667 
Modulo of vectors : 0 2 
Power operator : 0 8

Logical Operators

Logical Operators in R simulate element-wise decision operations, based on the specified operator between the operands, which are then evaluated to either a True or False boolean value. Any non-zero integer value is considered as a TRUE value, be it a complex or real number. 

Element-wise Logical AND operator (&)

Returns True if both the operands are True.

R
list1 <- c(TRUE, 0.1)
list2 <- c(0,4+3i)
print(list1 & list2)
Output : FALSE   TRUE
Any non zero integer value is considered as a TRUE value, be it complex or real number. 

Element-wise Logical OR operator (|)

Returns True if either of the operands is True.

R
list1 <- c(TRUE, 0.1)
list2 <- c(0,4+3i)
print(list1|list2)
Output : TRUE  TRUE

NOT operator (!)

A unary operator that negates the status of the elements of the operand.

R
list1 <- c(0,FALSE)
print(!list1)
Output : TRUE  TRUE

Logical AND operator (&&)

Returns True if both the first elements of the operands are True.

R
list1 <- c(TRUE, 0.1)
list2 <- c(0,4+3i)
print(list1[1] && list2[1])
Output : FALSE 
Compares just the first elements of both the lists.

Logical OR operator (||)

Returns True if either of the first elements of the operands is True.

R
list1 <- c(TRUE, 0.1)
list2 <- c(0,4+3i)
print(list1[1]||list2[1])
Output : TRUE 

The following R code illustrates the usage of all Logical Operators in R:  

R
# R program to illustrate 
# the use of Logical operators
vec1 <- c(0,2)
vec2 <- c(TRUE,FALSE)

# Performing operations on Operands
cat ("Element wise AND :", vec1 & vec2, "\n")
cat ("Element wise OR :", vec1 | vec2, "\n")
cat ("Logical AND :", vec1[1] && vec2[1], "\n")
cat ("Logical OR :", vec1[1] || vec2[1], "\n")
cat ("Negation :", !vec1)

Output 

Element wise AND : FALSE FALSE 
Element wise OR : TRUE TRUE 
Logical AND : FALSE 
Logical OR : TRUE 
Negation : TRUE FALSE

Relational Operators

The Relational Operators in R carry out comparison operations between the corresponding elements of the operands. Returns a boolean TRUE value if the first operand satisfies the relation compared to the second. A TRUE value is always considered to be greater than the FALSE. 

Less than (<)

Returns TRUE if the corresponding element of the first operand is less than that of the second operand. Else returns FALSE.

R
list1 <- c(TRUE, 0.1,"apple")
list2 <- c(0,0.1,"bat")
print(list1<list2)
Output :  FALSE FALSE  TRUE

Less than equal to (<=)

Returns TRUE if the corresponding element of the first operand is less than or equal to that of the second operand. Else returns FALSE.

R
list1 <- c(TRUE, 0.1, "apple")
list2 <- c(TRUE, 0.1, "bat")

# Convert lists to character strings
list1_char <- as.character(list1)
list2_char <- as.character(list2)

# Compare character strings
print(list1_char <= list2_char)
Output : TRUE TRUE TRUE

Greater than (>)

Returns TRUE if the corresponding element of the first operand is greater than that of the second operand. Else returns FALSE.

R
list1 <- c(TRUE, 0.1, "apple")
list2 <- c(TRUE, 0.1, "bat")
print(list1_char > list2_char)
Output : FALSE FALSE FALSE

Greater than equal to (>=)

Returns TRUE if the corresponding element of the first operand is greater or equal to that of the second operand. Else returns FALSE.

R
list1 <- c(TRUE, 0.1, "apple")
list2 <- c(TRUE, 0.1, "bat")
print(list1_char >= list2_char)
Output : TRUE TRUE FALSE

Not equal to (!=) 

Returns TRUE if the corresponding element of the first operand is not equal to the second operand. Else returns FALSE.

R
list1 <- c(TRUE, 0.1,'apple')
list2 <- c(0,0.1,"bat")
print(list1!=list2)
Output : TRUE FALSE TRUE

The following R code illustrates the usage of all Relational Operators in R:

R
# R program to illustrate 
# the use of Relational operators
vec1 <- c(0, 2)
vec2 <- c(2, 3)

# Performing operations on Operands
cat ("Vector1 less than Vector2 :", vec1 < vec2, "\n")
cat ("Vector1 less than equal to Vector2 :", vec1 <= vec2, "\n")
cat ("Vector1 greater than Vector2 :", vec1 > vec2, "\n")
cat ("Vector1 greater than equal to Vector2 :", vec1 >= vec2, "\n")
cat ("Vector1 not equal to Vector2 :", vec1 != vec2, "\n")

Output 

Vector1 less than Vector2 : TRUE TRUE 
Vector1 less than equal to Vector2 : TRUE TRUE 
Vector1 greater than Vector2 : FALSE FALSE 
Vector1 greater than equal to Vector2 : FALSE FALSE 
Vector1 not equal to Vector2 : TRUE TRUE 

Assignment Operators

Assignment Operators in R are used to assigning values to various data objects in R. The objects may be integers, vectors, or functions. These values are then stored by the assigned variable names. There are two kinds of assignment operators: Left and Right

Left Assignment (<- or <<- or =)

Assigns a value to a vector.

R
vec1 = c("ab", TRUE) 
print (vec1)
Output : "ab"   "TRUE"

Right Assignment (-> or ->>)

Assigns value to a vector.

R
c("ab", TRUE) ->> vec1
print (vec1)
Output : "ab"   "TRUE"

The following R code illustrates the usage of all Relational Operators in R:

R
# R program to illustrate 
# the use of Assignment operators
vec1 <- c(2:5)
c(2:5) ->> vec2
vec3 <<- c(2:5)
vec4 = c(2:5)
c(2:5) -> vec5

# Performing operations on Operands
cat ("vector 1 :", vec1, "\n")
cat("vector 2 :", vec2, "\n")
cat ("vector 3 :", vec3, "\n")
cat("vector 4 :", vec4, "\n")
cat("vector 5 :", vec5)

Output 

vector 1 : 2 3 4 5 
vector 2 : 2 3 4 5 
vector 3 : 2 3 4 5 
vector 4 : 2 3 4 5 
vector 5 : 2 3 4 5

Miscellaneous Operators

Miscellaneous Operator are the mixed operators in R that simulate the printing of sequences and assignment of vectors, either left or right-handed. 

%in% Operator 

Checks if an element belongs to a list and returns a boolean value TRUE if the value is present  else FALSE.

R
 val <- 0.1
 list1 <- c(TRUE, 0.1,"apple")
 print (val %in% list1)
Output : TRUE
Checks for the value 0.1 in the specified list. It exists, therefore, prints TRUE.

%*% Operator

This operator is used to multiply a matrix with its transpose. Transpose of the matrix is obtained by interchanging the rows to columns and columns to rows. The number of columns of the first matrix must be equal to the number of rows of the second matrix. Multiplication of the matrix A with its transpose, B, produces a square matrix. 
A_{r*c} x B_c*r -> P_{r*r}

R
 mat = matrix(c(1,2,3,4,5,6),nrow=2,ncol=3)
         print (mat)
         print( t(mat))
         pro = mat %*% t(mat)
         print(pro)
Input : 
Output :[,1] [,2] [,3]      #original matrix of order 2x3
        [1,]   1    3    5
        [2,]   2    4    6
             [,1] [,2]           #transposed matrix of order 3x2
        [1,]    1    2
        [2,]    3    4
        [3,]    5    6
             [,1] [,2]          #product matrix of order 2x2
        [1,]   35   44
        [2,]   44   56

The following R code illustrates the usage of all Miscellaneous Operators in R:

R
# R program to illustrate 
# the use of Miscellaneous operators
mat <- matrix (1:4, nrow = 1, ncol = 4)
print("Matrix elements using : ")
print(mat)

product = mat %*% t(mat)
print("Product of matrices")
print(product,)
cat ("does 1 exist in prod matrix :", "1" %in% product)

Output

[1] "Matrix elements using : "
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4

[1] "Product of matrices"
     [,1]
[1,]   30

does 1 exist in prod matrix : FALSE


Previous Article
Next Article

Similar Reads

What are Comparison Operators in R?
Comparison operators are fundamental tools in any programming language, allowing you to compare values and make decisions based on the results. In R Programming Language comparison operators are used to compare numeric, string, and other types of data. They return a logical value (TRUE or FALSE) based on the result of the comparison. This article p
3 min read
What are the Differences Between "=" and "<-" Assignment Operators in R?
In programming, assignment operators are essential tools for storing values in variables. In R, a statistical computing language, both "=" and "&lt;-" are used as assignment operators, but they are not the same. Understanding their differences can enhance your coding practice and improve your code's readability and functionality. Basic Understandin
3 min read
Data analysis using R
Data Analysis is a subset of data analytics, it is a process where the objective has to be made clear, collect the relevant data, preprocess the data, perform analysis(understand the data, explore insights), and then visualize it. The last step visualization is important to make people understand what's happening in the firm. Steps involved in data
5 min read
Frequency table in R
In this article, we are going to learn how to make a frequency table in the R programming language. Table of ContentFrequency TableOne-Way Frequency Tables in RTwo-Way Frequency Tables in RFrequency TableA frequency table is a list of objects with the frequency of each item shown in the table. When evaluating categorical data to determine how frequ
5 min read
How to Find and Count Missing Values in R DataFrame
In this article, we will be discussing how to find and count missing values in the R programming language. Find and Count Missing Values in the R DataFrameGenerally, missing values in the given data are represented with NA. In R programming, the missing values can be determined by is.na() method. This method accepts the data variable as a parameter
4 min read
A Guide to dnorm, pnorm, rnorm, and qnorm in R
In this article, we will be looking at a guide to the dnorm, pnorm, qnorm, and rnorm methods of the normal distribution in the R programming language. dnorm function This function returns the value of the probability density function (pdf) of the normal distribution given a certain random variable x, a population mean μ, and the population standard
3 min read
How to Change Axis Scales in R Plots?
In this article, we will learn how to change Axis Scales in the R Programming Language. Method 1: Change Axis Scales in Base R To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively. This fu
4 min read
Group by function in R using Dplyr
Group_by() function belongs to the dplyr package in the R programming language, which groups the data frames. Group_by() function alone will not give any output. It should be followed by summarise() function with an appropriate action to perform. It works similar to GROUP BY in SQL and pivot table in excel. Syntax: group_by(col,...) Syntax: group_b
2 min read
How to import an Excel File into R ?
In this article, we will discuss how to import an excel file in the R Programming Language. There two different types of approaches to import the excel file into the R programming language and those are discussed properly below. File in use: Method 1: Using read_excel() In this approach to import the Excel file in the R, the user needs to call the
3 min read
Change column name of a given DataFrame in R
A data frame is a tabular structure with fixed dimensions, of each rows as well as columns. It is a two-dimensional array like object with numerical, character based or factor-type data. Each element belonging to the data frame is indexed by a unique combination of the row and column number respectively. Column names are addressed by unique names.
5 min read
R Tutorial | Learn R Programming Language
R Programming Tutorial is designed for beginners and experts. This free R Tutorial gives you knowledge basic to advanced of concepts of the R programming language. Here you will get a detailed introduction, features, installation, variables, data types, operators, if statements, vectors, data handling, graphics, and statistical modeling of R progra
9 min read
R - Data Frames
R Programming Language is an open-source programming language that is widely used as a statistical software and data analysis tool. Data Frames in R Language are generic data objects of R that are used to store tabular data.  Data frames can also be interpreted as matrices where each column of a matrix can be of different data types. R DataFrame is
10 min read
Taking Input from User in R Programming
Developers often have a need to interact with users, either to get data or to provide some sort of result. Most programs today use a dialog box as a way of asking the user to provide some type of input. Like other programming languages in R it's also possible to take input from the user. For doing so, there are two methods in R. Using readline() me
7 min read
Printing Output of an R Program
In R there are various methods to print the output. Most common method to print output in R program, there is a function called print() is used. Also if the program of R is written over the console line by line then the output is printed normally, no need to use any function for print that output. To do this just select the output variable and pres
4 min read
Mean, Median and Mode in R Programming
Statistical measures like mean, median, and mode are essential for summarizing and understanding the central tendency of a dataset. In R, these measures can be calculated easily using built-in functions. This article will provide a comprehensive guide on how to calculate mean, median, and mode in R Programming Language. Dataset used for Calculating
5 min read
Read contents of a CSV File in R Programming - read.csv() Function
read.csv() function in R Language is used to read "comma separated value" files. It imports data in the form of a data frame. Syntax: read.csv(file, header, sep, dec) Parameters: file: the path to the file containing the data to be imported into R. header: logical value. If TRUE, read.csv() assumes that your file has a header row, so row 1 is the n
3 min read
How to Install R and R Studio?
Navigating the R language installation process and setting up R Studio is crucial for anyone looking to delve into data analysis, statistical computing, and graphical representation with R. In this article, we provide a step-by-step guide on how to install R and configure R Studio on your system. Whether you're a beginner taking your first steps in
6 min read
R - Matrices
R-matrix is a two-dimensional arrangement of data in rows and columns. In a matrix, rows are the ones that run horizontally and columns are the ones that run vertically. In R programming, matrices are two-dimensional, homogeneous data structures. These are some examples of matrices: Creating a Matrix in RTo create a matrix in R you need to use the
12 min read
R Programming for Data Science
ThisR Programming Language is an open-source programming language that is widely used as a statistical software and data analysis tool. R is an important tool for Data Science. It is highly popular and is the first choice of many statisticians and data scientists. But what makes R so popular? Why and How to Use R for Data Science? Data Science in R
5 min read
Basic Syntax in R Programming
R is the most popular language used for Statistical Computing and Data Analysis with the support of over 10, 000+ free packages in CRAN repository. Like any other programming language, R has a specific syntax which is important to understand if you want to make use of its powerful features. This article assumes R is already installed on your machin
3 min read
R Data Types
Different forms of data that can be saved and manipulated are defined and categorized using data types in computer languages, including R. Each R data type has unique properties and associated operations. What are R Data types?R Data types are used to specify the kind of data that can be stored in a variable. For effective memory consumption and pr
8 min read
R Factors
Factors in R Programming Language are data structures that are implemented to categorize the data or represent categorical data and store it on multiple levels. They can be stored as integers with a corresponding label to every unique integer. The R factors may look similar to character vectors, they are integers and care must be taken while using
5 min read
Getting started with Data Visualization in R
Data visualization is the technique used to deliver insights in data using visual cues such as graphs, charts, maps, and many others. This is useful as it helps in intuitive and easy understanding of the large quantities of data and thereby make better decisions regarding it. Data Visualization in R Programming LanguageThe popular data visualizatio
6 min read
Normal Distribution in R
Normal Distribution is a probability function used in statistics that tells about how the data values are distributed. It is the most important probability distribution function used in statistics because of its advantages in real case scenarios. For example, the height of the population, shoe size, IQ level, rolling a dice, and many more. It is ge
3 min read
R Vectors
R Vectors are the same as the arrays in R language which are used to hold multiple data values of the same type. One major key point is that in R Programming Language the indexing of the vector will start from '1' and not from '0'. We can create numeric vectors and character vectors as well.  Creating a vectorA vector is a basic data structure that
5 min read
R Operators
Operators are the symbols directing the compiler to perform various kinds of operations between the operands. Operators simulate the various mathematical, logical, and decision operations performed on a set of Complex Numbers, Integers, and Numericals as input operands. R Operators R supports majorly four kinds of binary operators between a set of
9 min read
R Programming Language - Introduction
The R Language stands out as a powerful tool in the modern era of statistical computing and data analysis. Widely embraced by statisticians, data scientists, and researchers, the R Language offers an extensive suite of packages and libraries tailored for data manipulation, statistical modeling, and visualization. In this article, we explore the fea
7 min read
Histograms in R language
A histogram contains a rectangular area to display the statistical information which is proportional to the frequency of a variable and its width in successive numerical intervals. A graphical representation that manages a group of data points into different specified ranges. It has a special feature that shows no gaps between the bars and is simil
3 min read
R - Bar Charts
Bar charts are a popular and effective way to visually represent categorical data in a structured manner. R stands out as a powerful programming language for data analysis and visualization. In this article, we'll look at how to make visually appealing bar charts in R. Bar Charts using RA bar chart also known as bar graph is a pictorial representat
5 min read
Simple Linear Regression in R
Regression shows a line or curve that passes through all the data points on the target-predictor graph in such a way that the vertical distance between the data points and the regression line is minimum What is Linear Regression?Linear Regression is a commonly used type of predictive analysis. Linear Regression is a statistical approach for modelli
12 min read
Article Tags :