Operators in R
In R programming, operators are special symbols that represent computations, such as arithmetic operations, comparison, logical operations, and more. Indeed, they are the building blocks of any programming language. In this tutorial, we are going to learn about the different types of operators in R and how to use them.
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations. The basic arithmetic operators in R are:
+
Addition-
Subtraction*
Multiplication/
Division%%
Modulus (returns the remainder of the division)%/%
Integer Division (returns quotient of the division)^
or**
Exponentiation
Here's an example:
x <- 15
y <- 5
# Addition
x + y
# Subtraction
x - y
# Multiplication
x * y
# Division
x / y
# Modulus
x %% y
# Integer Division
x %/% y
# Exponentiation
x ^ y
Relational Operators
Relational operators are used to compare between variables. The basic relational operators in R are:
>
Greater than<
Less than==
Equal to!=
Not equal to>=
Greater than or equal to<=
Less than or equal to
Here's an example:
x <- 10
y <- 20
# Greater than
x > y
# Less than
x < y
# Equal to
x == y
# Not equal to
x != y
# Greater than or equal to
x >= y
# Less than or equal to
x <= y
Logical Operators
Logical operators are used to perform logical operations. The basic logical operators in R are:
&
Logical AND|
Logical OR!
Logical NOT&&
AND||
OR
Here's an example:
x <- TRUE
y <- FALSE
# Logical AND
x & y
# Logical OR
x | y
# Logical NOT
!x
# AND
x && y
# OR
x || y
Assignment Operators
Assignment operators are used to assign values to variables. The basic assignment operators in R are:
<-
or=
or<<-
Assign value on the right to the variable on the left->
Assign value on the left to the variable on the right
Here's an example:
# Assign value on the right to the variable on the left
x <- 10
y = 20
z <<- 30
# Assign value on the left to the variable on the right
10 -> x
Miscellaneous Operators
R also supports some miscellaneous operators:
:
The colon operator, creates a sequence of numbers in from:to fashion.%in%
The operator identifies if an element belongs to a vector.%*%
The operator multiplies a matrix by another matrix.
Here's an example:
# The colon operator
1:10
# %in% operator
5 %in% 1:10
# %*% operator
matrix(1:4, 2, 2) %*% matrix(1:4, 2, 2)
And that's a wrap! Now you have a basic understanding of how to use different types of operators in R. Remember, understanding and practicing these operators will help you build a solid foundation in R programming. Happy Coding!