<- 227
x <- 639 y
Introduction
R has many different types of operators that can perform different tasks.
Here we will focus on 5 major types of operators. The major types of operators are:
Arithmetic,
Relational,
Logical,
Assignment, and
Miscellaneous.
1. Arithmetic Operators
Arithmetic operators are used to perform mathematical operations. These operators have been highlighted in Part 1 of the series.
2. Relational Operators
Relational operators are used to find the relationship between 2 variables and compare objects. The output of these comparisons is Boolean (TRUE
or FALSE
). The table below describes the most common relational operators.
Relational Operator | Description |
---|---|
< | Less than |
> | Greater than |
<= | Less than or equal to |
>= | Greater than or equal to |
== | Equal to |
!= | Not Equal to |
Assign values to variables
a. Less than
< y x
[1] TRUE
b. Greater than
> y x
[1] FALSE
c. Less than or equal to
<= 300 x
[1] TRUE
d. Greater than or equal to
>= 700 y
[1] FALSE
e. Equal to
== 639 y
[1] TRUE
f. Not Equal to
!= 227 x
[1] FALSE
3. Logical Operators
Logical operators are used to specify multiple conditions between objects. Logical operators work with basic data types such as logical, numeric, and complex data types. This returns TRUE
or FALSE
values. Numbers greater that 1
are TRUE
and 0
equals FALSE
. The table below describes the most common logical operators.
Logical Operator | Description |
---|---|
! | Logical NOT |
| | Element-wise logical OR |
& | Element-wise logical AND |
Assign vectors to variables
<- c(0,2)
vector_1 <- c(1,0) vector_2
a. Logical NOT
!vector_1
[1] TRUE FALSE
!vector_2
[1] FALSE TRUE
b. Element-wise Logical OR
| vector_2 vector_1
[1] TRUE TRUE
c. Element-wise Logical AND
& vector_2 vector_1
[1] FALSE FALSE
4. Assignment Operators
These operators assign values to variables. A more comprehensive review can be obtained in Part 2 of the series.
5. Miscellaneous Operators
These are helpful operators for working in that can perform a variety of functions. A few common miscellaneous operators are described below.
Miscellaneous Operator | Description |
---|---|
%*% | Matrix multiplication (to be discussed in subsequent chapters) |
%in% | Does an element belong to a vector |
: | Generate a sequence |
a. Sequence
<- 1:8
a a
[1] 1 2 3 4 5 6 7 8
<- 4:10
b b
[1] 4 5 6 7 8 9 10
b. Element in a vector
%in% b a
[1] FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE
9 %in% b
[1] TRUE
9 %in% a
[1] FALSE