Operators are symbols in R used to perform operations between the operands. They are categorized into several types: arithmetic, relational, logical, assignment, and miscellaneous operators. In this article, I will cover each type of operator in R programming and show how to use them for various operations involving complex numbers, integers, and numeric values as operands.
- Relational Operators
- Logical Operators
- Arithmetic Operators
- Assignment Operators
- Miscellaneous Operators
Key Points:
- Relational Operators are used to compare values and return logical results (TRUE or FALSE).
- Logical Operators perform Boolean logic operations on logical data, such as AND, OR, and NOT.
- Arithmetic Operators handle basic mathematical operations like addition, subtraction, multiplication, division, and exponentiation.
- Assignment Operators assign values to variables in R, including left and right assignment operators.
- Miscellaneous Operators include operators like
%in%
for checking membership and%*%
for matrix multiplication. - Equality (==) and Inequality (!=) operators compare the equality of values.
- Logical AND (&, &&) and Logical OR (|, ||) operators combine multiple logical conditions.
- The remainder and quotient of division operations are obtained using the Modulo (%%) and Integer Division (%/%) operators.
- The Power (^) operator is used to raise a number to a specified exponent.
- Understanding the behavior of operators in different contexts (e.g., vectors, matrices) is crucial for accurate data analysis and manipulation in R.
Relational Operators in R
Relational operators or comparators in R are used to compare operands, which can be values or variables. These operators return a logical value (TRUE
or FALSE
) depending on whether specified conditions are met. They are particularly useful for performing conditional checks in R, with TRUE
indicating a successful condition (e.g., greater than, equal to) and holding a higher logical value than FALSE
.
The table below presents relational operator symbols along with their descriptions.
Operator | Description |
---|---|
== | Equal to |
!= | Not equal to |
> | Greater than |
< | Less than |
>= | Greater or equal |
<= | Less or equal |
Let’s use relational operators in R to determine the relationship between different values.
Using Equality (==) Operator
You can apply the equality(==
) operator to numbers, strings, and vectors to perform comparison in R. For vectors, comparisons are performed element-wise, returning a logical vector (TRUE
or FALSE
). Each successful comparison returns TRUE
; otherwise, it returns FALSE
.
# Comparing vectors using == operator
# Create vectors
vec1 <- c(2.1, "R", 6)
vec2 <- c(2.4, "R", 5)
print("First vector:")
print(vec1)
print("Second vector:")
print(vec2)
result <- vec1 == vec2
print("After comparing the vectors:")
print(result)
Yields below output.
Using Inequality != Operator
Unlike the equality operator (==
), this operator returns TRUE
for each element where the condition is not met, and FALSE
for each successful match. Let’s apply it to vectors to see how it operates on each element.
# Comparing vectors using != operator
# Create vectors
vec1 <- c(2.1, "R", 6)
vec2 <- c(2.4, "R", 5)
print("First vector:")
print(vec1)
print("Second vector:")
print(vec2)
result <- vec1 != vec2
print("After comparing the vectors:")
print(result)
Yields below output.
Using < and > Operators
You can compare elements of one vector with another using the less than (<
) or greater than (>
) operators to check if elements are smaller or larger.
# Comparing vectors using < and > operators
# Create vectors
vec1 <- c(2.1, "R", 6)
vec2 <- c(2.4, "Python", 5)
# Comparing vectors using < opertor
result <- vec1 < vec2
print("After comparing the vectors:")
print(result)
# Output:
# "After comparing the vectors:"
# [1] TRUE FALSE FALSE
# Comparing vectors using < opertor
result <- vec1 > vec2
print("After comparing the vectors:")
print(result)
# Output:
# "After comparing the vectors:"
# [1] FALSE TRUE TRUE
Using Operator <= and >=
You can also use the less than or equal to (<=
) and greater than or equal to (>=
) operators to compare elements between two vectors, checking if elements are smaller or larger.
# Comparing vectors using <= operator
result <- vec1 <= vec2
print("After comparing the vectors:")
print(result)
# Output:
# [1] "After comparing the vectors:"
# [1] TRUE FALSE FALSE
# Comparing vectors using >= operator
result <- vec1 >= vec2
print("After comparing the vectors:")
print(result)
# Output:
# [1] "After comparing the vectors:"
# [1] FALSE TRUE TRUE
Logical Operators in R
Logical operators in R perform Boolean logic operations and are often used in control structures and data filtering to combine multiple conditions. In logical expressions, any non-zero integer—whether real or complex—is evaluated as TRUE
. These operators work with numeric, logical, or complex data types.
Operator | Description |
---|---|
& | Element-wise Logical AND operator. Returns TRUE if both statements are TRUE |
&& | Logical AND operator – Returns TRUE if both statements are TRUE |
| | Elementwise- Logical OR operator. Returns TRUE if one of the statements is TRUE |
|| | Logical OR operator. Returns TRUE if one of the statements is TRUE |
! | Logical NOT – Returns FALSE if statement is TRUE |
Element-wise Logical AND operator(&)
The &
operator performs element-wise logical AND between two vectors. In R, any non-zero number (real or complex) is considered TRUE
, while 0
is considered FALSE
. It returns TRUE
if both statements are TRUE
.
# Perform logical operation using & operator
vec1 <- c(TRUE, 6)
vec2 <- c(2+4i, 0)
print("First vector:")
print(vec1)
print("Second vector:")
print(vec2)
print("Result:")
result <- vec1 & vec2
print(result)
# Output:
# [1] "First vector:"
# [1] 1 6
# [1] "Second vector:"
# [1] 2+4i 0+0i
# Result:
# [1] TRUE FALSE
Element-wise Logical OR operator (|)
The |
operator performs element-wise logical OR between two vectors. In R, any non-zero number (real or complex) is considered TRUE
, while 0
is considered FALSE
. It returns TRUE
if one of the statements is TRUE
.
# Perform logical operation using | operator
vec1 <- c(TRUE, 0)
vec2 <- c(2+4i, 0)
print("First vector:")
print(vec1)
print("Second vector:")
print(vec2)
result <- vec1 | vec2
print("Result:")
print(result)
# Output:
# [1] "First vector:"
# [1] 1 0
# [1] "Second vector:"
# [1] 2+4i 0+0i
# [1] "Result:"
# [1] TRUE FALSE
NOT operator (!)
The NOT(!
) operator inverts logical values. TRUE
becomes FALSE
, and FALSE
becomes TRUE
. Let’s apply the negation of the result to get the opposite logical value of the result.
# Perform logical operation using ! operator
vec <- c(TRUE, 0)
print("Given vector:")
vec
result <- ! vec
print("Result:")
print(result)
# Output:
# [1] "Result:"
# [1] FALSE TRUE
Logical AND operator (&&)
The &&
operator performs a logical AND on the specific elements of two vectors. It returns TRUE
only if both elements are TRUE
.
# Perform logical operation using && operator
vec1 <- c(TRUE, 6)
vec2 <- c(2+4i, 0)
print("First vector:")
print(vec1)
print("Second vector:")
print(vec2)
print("Result:")
result <- vec1[2] && vec2[2]
print(result)
# Output:
# [1] "First vector:"
# [1] 1 6
# [1] "Second vector:"
# [1] 2+4i 0+0i
# [1] "Result:"
# [1] FALSE
Logical OR operator (||)
The ||
operator performs a logical OR on the specific elements of two vectors. It returns TRUE
if at least one element is TRUE
.
# Perform logical operation using || operator
vec1 <- c(TRUE, 6)
vec2 <- c(2+4i, 0)
print("First vector:")
print(vec1)
print("Second vector:")
print(vec2)
print("Result:")
result <- vec1[1] || vec2[1]
print(result)
# Output:
# [1] "First vector:"
# [1] 1 6
# [1] "Second vector:"
# [1] 2+4i 0+0i
# [1] "Result:"
# [1] TRUE
Arithmetic Operators in R
These R arithmetic operators are used to compute mathematical operations like addition, subtraction, multiplication, division, and modulo using the specified add operator between operands, which may be either scalar values, complex numbers, or vectors. The operations are performed element-wise at the corresponding positions of the vectors. Below is the list of arithmetic operators available in R.
Arithmetic operators are used for basic mathematical operations.
Operator | Description | Example | Result |
---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 5 - 3 | 2 |
* | Multiplication | 5 * 3 | 15 |
/ | Division | 5 / 3 | 1.67 |
^ or ** | Exponentiation | 5 ^ 3 or 5 ** 3 | 125 |
%% | Modulus | 5 %% 3 | 2 |
%/% | Integer Division | 5 %/% 3 | 1 |
Addition operator (+)
You can use the +
operator to add the values at the corresponding positions of two vectors. Let’s perform addition on the corresponding elements of both vectors.
# Perform arithamatic operation using + operator
vec1 <- c(5, 10)
vec2 <- c(15, 20)
print("First vector:")
print(vec1)
print("Second vector:")
print(vec2)
print("After addding two vectors:")
result <- vec1 + vec2
print(result)
# Output:
# [1] "First vector:"
# [1] 5 10
# [1] "Second vector:"
# [1] 15 20
# [1] "After addding two vectors:"
# [1] 20 30
Subtraction Operator (-)
You can use the -
operator to subtract the values of the second vector from the corresponding values of the first vector. Let’s subtract the elements of the second vector from the first.
# Perform arithamatic operation using - operator
vec1 <- c(5, 10)
vec2 <- c(15, 20)
print("First vector:")
print(vec1)
print("Second vector:")
print(vec2)
print("After subtracting two vectors:")
result <- vec1 - vec2
print(result)
# Output:
# [1] "First vector:"
# [1] 5 10
# [1] "Second vector:"
# [1] 15 20
# [1] "After subtracting two vectors:"
# [1] -10 -10
Multiplication Operator (*)
To multiply corresponding elements in two vectors you can use multiplication(*
) operator. Let’s apply this operator to get the resulting vector where the values are products.
# Perform arithamatic operation using * operator
vec1 <- c(5, 10)
vec2 <- c(15, 20)
print("First vector:")
print(vec1)
print("Second vector:")
print(vec2)
print("After multiplying two vectors:")
result <- vec1 * vec2
print(result)
# Output:
# [1] "First vector:"
# [1] 5 10
# [1] "Second vector:"
# [1] 15 20
# [1] "After multiplying two vectors:"
# [1] 75 200
Division Operator (/)
You can use the division (/
) operator between two vectors, where the first operand is divided by the second operand.
# Perform arithamatic operation using / operator
vec1 <- c(5, 10)
vec2 <- c(15, 20)
print("First vector:")
print(vec1)
print("Second vector:")
print(vec2)
print("After dividing two vectors:")
result <- vec1 / vec2
print(result)
# Output:
# [1] "First vector:"
# [1] 5 10
# [1] "Second vector:"
# [1] 15 20
# [1] "After dividing two vectors:"
# [1] [1] 0.3333333 0.5000000
Power Operator (^)
When we use the power (^
) operator between two vectors, the first operand is raised to the power of the second operand.
# Perform arithamatic operation using ^ operator
x <- 10
y <- 2
print("After getting exponential:")
result <- x ^ y
print(result)
# Output:
# [1] "After getting exponential:"
# [1] 100
Modulo Operator (%%)
The Modulo (%%
) operator is used between two vectors to return the remainder when the first operand is divided by the second operand.
# Perform arithamatic operation using %% operator
vec1 <- c(5, 20)
vec2 <- c(2, 4)
print("First vector:")
print(vec1)
print("Second vector:")
print(vec2)
print("After getting modulo of two vectors:")
result <- vec1 %% vec2
print(result)
# Output:
# [1] "First vector:"
# [1] 5 20
# [1] "Second vector:"
# [1] 2 4
# [1] "After getting modulo of two vectors:"
# [1] 1 0
Integer Division (%/%)
The Integer Division (%/%
) operator is used between two vectors to divide the first operand by the second operand and return the integer quotient, discarding the remainder.
# Perform arithamatic operation using %/% operator
vec1 <- c(5, 20)
vec2 <- c(2, 4)
print("First vector:")
print(vec1)
print("Second vector:")
print(vec2)
print("After getting integer division of two vectors:")
result <- vec1 %/% vec2
print(result)
# Output:
# [1] "First vector:"
# [1] 5 20
# [1] "Second vector:"
# [1] 2 4
# [1] "After getting integer division of two vectors:"
# [1] 2 5
Assignment Operators in R
Assignment operators are used to assign values to variables in R.
Operator | Description | Example |
---|---|---|
<- | Leftward assign | x <- 5 |
-> | Rightward assign | 5 -> x |
<<- | Global assign | x <<- 5 |
= | Assign (in functions, usually) | y = 10 |
Left Assignment (<- or <<- or =)
The Left Assignment (<-
, <<-
, =
) operators are used to assign values to variables. The <-
and =
operators are commonly used for local assignments, while <<-
is used for assigning values to variables in the global environment.
# Assign values to vectors using left assignment(<-, <<-, and =)
vec1 = c(10, TRUE)
vec2 <- c(20, FALSE)
vec3 <<- c(30, "R")
print("First vector:")
print (vec1)
print("Second vector:")
print (vec2)
print("Third vector:")
print (vec3)
# Output:
# [1] "First vector:"
# [1] 10 1
# [1] "Second vector:"
# [1] 20 0
# [1] "Third vector:"
# [1] "30" "R"
Right Assignment (-> or ->>)
The Right Assignment (->
, ->>
) operators are used to assign values to variables, with the variable specified on the right side of the assignment. ->
is used for local assignments, while ->>
is used for assigning values to variables in the global environment.
# Assign values to vectors using right assignment(-> and ->>)
c(10, TRUE) -> vec1
c(20, FALSE) ->> vec2
print("First vector:")
print (vec1)
print("Second vector:")
print (vec2)
# Output:
# [1] "First vector:"
# [1] 10 1
# [1] "Second vector:"
# [1] 20 0
Miscellaneous Operators in R
Miscellaneous Operators in R include operators that handle specific tasks, such as checking membership or matrix operations. Two notable examples are:
%in% Operator
You can use the %in% operator to check if an element exists in a vector or a list, returning TRUE
if the element is found, and FALSE
otherwise.
# Use %in% operator to check existence of value
x <- 10
vec1 <- c(10, 20 ,30)
print (x %in% vec1)
# Output:
# TRUE
%*% Operator
You can use the %*%
operator to perform matrix multiplication, which multiplies a matrix by another matrix or its transpose. The transpose of a matrix is obtained by swapping its rows and columns.
Let’s apply this operator between a matrix and its transpose to obtain a squared matrix, where the values represent the products of the two matrices.
# Use %*%operator to perform matrix multiplictaion
mat = matrix(c(1:6), nrow=2, ncol=3)
print("Given matrix:")
print(mat)
print("Transpose of matrix:")
print(t(mat))
product = mat %*% t(mat)
print("Product of matrix:")
print(product)
# Output:
# [1] "Given matrix:"
# [,1] [,2] [,3]
# [1,] 1 3 5
# [2,] 2 4 6
# [1]"Trnspose of matrix:"
# [,1] [,2]
# [1,] 1 2
# [2,] 3 4
# [3,] 5 6
# [1] "Product of matrix:"
# [,1] [,2]
# [1,] 35 44
# [2,] 44 56
Frequently Asked Questions of Operators in R
Operators in R are symbols that represent specific operations to be performed on operands. They are essential in R for performing various tasks, such as arithmetic calculations, logical comparisons, and data manipulation, making them a foundational part of programming in R.
R supports vectorized operations, meaning arithmetic, relational, and logical operators can work on vectors element-wise. This feature allows you to perform operations on each element of a vector simultaneously without writing a loop, making R highly efficient for data processing tasks.
==
is a relational operator used for equality comparison, returning TRUE
or FALSE
based on whether the values are equal. =
is an assignment operator commonly used to assign values to variables, although <-
is more typical for assignment in R.
The %in%
operator checks if a specified element exists within a vector or list. It returns TRUE
if the element is found, and FALSE
otherwise. This is useful for tasks like data filtering and conditional checks
Both &
and &&
are logical AND operators, but &
performs element-wise comparisons on vectors, while &&
only evaluates the first element of each vector. &&
is typically used in control flow statements where only the first element is of interest.
The %*%
operator performs matrix multiplication, which requires that the number of columns in the first matrix matches the number of rows in the second. Unlike element-wise multiplication, %*%
follows matrix multiplication rules, resulting in a new matrix.
The %%
operator returns the remainder of a division operation. For example, 5 %% 2
results in 1
, as it is the remainder when 5 is divided by 2.
Conclusion
In this article, I have explained R operators, which are the basic functions that we use to perform operations on data. They allow you to perform mathematical operations, compare values, store data in variables, and set logic conditions. Various operators are used in R for various operations, such as arithmetic operators (for addition and multiplication), relational operators (for comparing variables as true or false), logical operators (useful for comparing raw data patterns at certain levels), and assignment (like <-
to assign values to variables). Understanding these types of operators in R helps users perform both simple and complex tasks, from basic data manipulation to advanced data analysis. With these operators, users can manipulate vectors, matrices, and a variety of other data structures in R easily and quickly, ultimately building towards more advanced R programming expertise and tackling complex operations.
Happy Learning!!