R Operators

Operators are used to perform operations on variables and values.

Types of Operators in R

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

Arithmetic operators

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

OperatorNameExample
+Additionx + y
Subtractionx – y
*Multiplicationx * y
/Divisionx / y
%%Modulus (Remainder from division)x %% y
%/%Integer Divisionx%/%y

Assignment Operators

Assignment operators are used to assign values to variables:

Comparison operators

OperatorNameCode Example
==Equalx == y
!=Not equalx != y
>Greater thanx > y
<Less thanx < y
>=Greater than or equalx >= y
<=Less than or equalx <= y
%in%Element ofx %in% c(1, 2, 3)
isTRUE()TrueisTRUE(x > y)
identical()Identicalidentical(x, y)
The %in% operator is used to test if elements on the left-hand side are members of the set on the right-hand side.
The isTRUE() function is used to test if a condition is true.
The identical() function is used to test if two objects are identical.

Note:

Logical Operators

Logical operators return a logical data type such as TRUE or FALSE

Types of Logical Operators

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

Conditional Operators

OperatorDescriptionCode Example
if()The if statement sets a condition, and if the condition evaluates to TRUE, the the R code associated with the statement is executed. The code that is executed is called the expression. This expression is in curly braces {}.
if(condition){ expression }
x <- 5
y <- 7
if(y > x) {
print(“y is greater than x.”)
}
else()The else() statement is used in combination with the if() statement. The else statement is executed if the the if() is not true.if (y<x){
print(“y is less than x”)
}else{
print(“y is greate than x”)
}
else if()The else if() comes between the if statement and the else statementx <- 5 y <- 7 if(x> y) {
print(“y is greater than x.”)
}else if(y==x){
print(“y is equal to x”)
}else{
print(“y is greater than x”)
}

A conditional statement is a declaration that if a certain condition holds, then a certain event must take place.

    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

    Other Operators

    Leave a Comment

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

    Scroll to Top