R Operators


Operators

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Example

10 + 5

R divides the operators in the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Miscellaneous operators

R Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:

OperatorNameExampleTry it
+Additionx + yTry it »
Subtractionx – yTry it »
*Multiplicationx * yTry it »
/Divisionx / yTry it »
^Exponentx ^ yTry it »
%%Modulus (Remainder from division)x %% yTry it »
%/%Integer Divisionx%/%yTry it »

R Assignment Operators

Assignment operators are used to assign values to variables:

Example

my_var <- 3
my_var <<- 3
3 -> my_var
3 ->> my_var
my_var # print my_var

It is also possible to turn the direction of the assignment operator.

x <- 3 is equal to 3 -> x

ADVERTISEMENT


R Comparison Operators

Comparison operators are used to compare two values:

OperatorNameExampleTry it
==Equalx == yTry it »
!=Not equalx != yTry it »
>Greater thanx > yTry it »
<Less thanx < yTry it »
>=Greater than or equal tox >= yTry it »
<=Less than or equal tox <= yTry it »

R Logical Operators

Logical operators are used to combine conditional statements:

OperatorDescription
&Element-wise Logical AND operator. It returns TRUE if both elements are TRUE
&&Logical AND operator – Returns TRUE if both statements are TRUE
|Elementwise- Logical OR operator. It returns TRUE if one of the statement is TRUE
||Logical OR operator. It returns TRUE if one of the statement is TRUE.
!Logical NOT – returns FALSE if statement is TRUE

R Miscellaneous Operators

Miscellaneous operators are used to manipulate data:

OperatorDescriptionExample
:Creates a series of numbers in a sequencex <- 1:10
%in%Find out if an element belongs to a vectorx %in% y
%*%Matrix Multiplicationx <- Matrix1 %*% Matrix2