The Basics of R and RStudio

Part 4: Operators

RStudio
R
Tutorial
Blog
Author

William Okech

Published

November 9, 2022

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:

  1. Arithmetic,

  2. Relational,

  3. Logical,

  4. Assignment, and

  5. 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

x <- 227
y <- 639

a. Less than

x < y
[1] TRUE

b. Greater than

x > y
[1] FALSE

c. Less than or equal to

x <= 300
[1] TRUE

d. Greater than or equal to

y >= 700
[1] FALSE

e. Equal to

y == 639
[1] TRUE

f. Not Equal to

x != 227
[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

vector_1 <- c(0,2)
vector_2 <- c(1,0)

a. Logical NOT

!vector_1
[1]  TRUE FALSE
!vector_2
[1] FALSE  TRUE

b. Element-wise Logical OR

vector_1 | vector_2
[1] TRUE TRUE

c. Element-wise Logical AND

vector_1 & vector_2
[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

a <- 1:8
a
[1] 1 2 3 4 5 6 7 8
b <- 4:10
b
[1]  4  5  6  7  8  9 10

b. Element in a vector

a %in% b
[1] FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE
9 %in% b
[1] TRUE
9 %in% a
[1] FALSE