R Operators

There are the following types of operators in R.
  • Arithmetic Operators
  • Assignment Operators
  • Logical Operators
  • Comparison Operators
  • Miscellaneous Operators


Arithmetic Operators

Arithmetic operators work on only two numeric operands, if the operands are not numeric then it automatically converts to numeric.

Operator Name Example
+ Addition v1 <- c(4, 5, 6)
v2 <- c(1.4, 2.5, 3.2)
print(v1+v2)
- Subtraction v1 <- c(4, 5, 6)
v2 <- c(1.4, 2.5, 3.2)
print(v1-v2)
* Multiplication v1 <- c(4, 5, 6)
v2 <- c(1.4, 2.5, 3.2)
print(v1*v2)
/ Division v1 <- c(4, 5, 6)
v2 <- c(1.4, 2.5, 3.2)
print(v1/v2)
%% Modulus v1 <- c(4, 5, 6)
v2 <- c(1.4, 2.5, 3.2)
print(v1%%v2)
%/% Integer Division v1 <- c(4, 5, 6)
v2 <- c(1.4, 2.5, 3.2)
print(v1%/%v2)




Assignment Operators

Assignment operators assign a value to a variable, it assigns the value of its right operand to its left operand and also it can assign the value of its left operand to its right operand.

Operator Name Examples
<-, <<-, = Leftwards assignment x <- 10
->, ->> Rightwards assignment c(10, 3) -> y

Logical Operators

These operators are used to perform logical operations. It returns the result in always a boolean value, it returns true if either or both operands are true, and returns false otherwise.

Operator Name Example
& Element wise logical AND v1 <- c(4, 5, 6)
v2 <- c(1.4, 2.5, 3.2)
print(v1&v2)
&& Logical AND v1 <- c(4, 5, 6)
v2 <- c(1.4, 2.5, 3.2)
print(v1&&v2)
| Element wise logical OR v1 <- c(4, 5, 6)
v2 <- c(1.4, 2.5, 3.2)
print(v1|v2)
|| Logical OR v1 <- c(4, 5, 6)
v2 <- c(1.4, 2.5, 3.2)
print(v1||v2)
! Logical NOT v1 <- c(4, 5, 6)
print(!v1)




Comparison Operators

Comparison operators are used for comparison and are mostly used either in if conditions or loops. Its result is always a boolean value.

Operator Name Example
== Equal to v1 <- c(4, 5, 6)
v2 <- c(4, 2.5, 6)
print(v1==v2)
!= Not equal to v1 <- c(4, 5, 6)
v2 <- c(4, 2.5, 6)
print(v1!=v2)
< Less than v1 <- c(4, 5, 6)
v2 <- c(4, 2.5, 6)
print(v1 < v2)
> Greater than v1 <- c(4, 5, 6)
v2 <- c(4, 2.5, 6)
print(v1 > v2)
>= Greater than equal to v1 <- c(4, 5, 6)
v2 <- c(4, 2.5, 6)
print(v1 >= v2)
<= Less than equal to v1 <- c(4, 5, 6)
v2 <- c(4, 2.5, 6)
print(v1 <= v2)




Miscellaneous Operators

Operator Name Example
: Colon Operator v <- 1:10
%in% Belongs to Operator v1 <- 4
v2 <- 1:10
print(v1 %in% v2)
%*% Vector multiplication with its transpose M <- matrix(c(1,2,3), nrow=2, ncol=3, TRUE) print(M%*%t(M))

Colon Operator (:)- The colon operator generates a regular sequence, which is equivalent to interaction(a,b) but the levels are ordered and labelled differently.

Belongs to Operator (%in%) - The %in% operator identifies whether an element belongs to a vector or not.

Vector multiplication with its transpose (%*%) - The %*% operator performs multiplication of a vector with its transpose.







Read more articles


General Knowledge



Learn Popular Language