R has many operators to carry out different mathematical and logical operations. Operators perform tasks including arithmetic, logical and bitwise operations.
Type of operators in R
Operators in R can mainly be classified into the following categories:
- Arithmetic Operators
- Relational Operators
- Logical Operators
- Assignment Operators
R Arithmetic Operators
These operators are used to carry out mathematical operations like addition and multiplication. Here is a list of arithmetic operators available in R.
|%%||Modulus(Remainder from division)|
Let's look at an example illustrating the use of the above operators:
x <- 5 y <- 16 x + y x - y x * y y / x y %/% x y %% x y ^ x
 21  -11  80  3.2  3  1  1048576
R Relational Operators
Relational operators are used to compare between values. Here is a list of relational operators available in R.
|Less than or equal to|
|>=||Greater than or equal to|
|!=||Not equal to|
Let's see an example for this:
x <- 5 y <- 16 x < y x > y x <= 5 y >= 20 y == 16 x != 5
 TRUE  FALSE  TRUE  FALSE  TRUE  FALSE
Operation on Vectors
The above mentioned operators work on vectors. The variables used above were in fact single element vectors.
We can use the function
c() (as in concatenate) to make vectors in R.
All operations are carried out in element-wise fashion. Here is an example.
x <- c(2, 8, 3) y <- c(6, 4, 1) x + y x > y
 8 12 4  FALSE TRUE TRUE
When there is a mismatch in length (number of elements) of operand vectors, the elements in the shorter one are recycled in a cyclic manner to match the length of the longer one.
R will issue a warning if the length of the longer vector is not an integral multiple of the shorter vector.
x <- c(2, 1, 8, 3) y <- c(9, 4) x + y x - 1 x + c(1, 2, 3)
 11 5 17 7 1 0 7 2  3 3 11 4 Warning message: In x + c(1, 2, 3) : longer object length is not a multiple of shorter object length
R Logical Operators
Logical operators are used to carry out Boolean operations like
|&||Element-wise logical AND|
||||Element-wise logical OR|
| perform element-wise operation producing result having length of the longer operand.
|| examines only the first element of the operands resulting in a single length logical vector.
Zero is considered
FALSE and non-zero numbers are taken as
TRUE. Let's see an example for this:
x <- c(TRUE, FALSE, 0, 6) y <- c(FALSE, TRUE, FALSE, TRUE) !x x & y x && y x | y x || y
 FALSE TRUE TRUE FALSE  FALSE FALSE FALSE TRUE  FALSE  TRUE TRUE FALSE TRUE  TRUE
R Assignment Operators
These operators are used to assign values to variables.
|->, ->>||Rightwards assignment|
= can be used, almost interchangeably, to assign to variables in the same environment.
<<- operator is used for assigning to variables in the parent environments (more like global assignments). The rightward assignments, although available, are rarely used.
x <- 5 x x <- 9 x 10 -> x x
 5  9  10
Check out these examples to learn more: