Operators

What are operators in R?

Operators in R are symbols or keywords that perform specific operations on data

 

Categories of Operators in R

Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Miscellaneous operators

 

Arithmetic Operators

 

Name Operator Example
Addition + A + B
Subtraction A-B
Multiplication * A*B
Division / A/B
Exponent ^ A^B
Modulus %% A %%B
Integer %/% A%/%B

a <- 5
b <- 3

# Addition
sum <- a + b

# Subtraction
difference <- a – b

# Multiplication
product <- a * b

# Division
quotient <- a / b

# Exponentiation
power <- a^b

Assignment Operators

Are used to assign values to variables and vectors.

<- and =

# Using <- operator
x <- 10

# Using = operator
y = 20

Global Assignment
<<-

# Assigning a value to a variable in the global environment
my_global <- function() {
x <<- 30
}

R Logical Operators

Logical operators are used to combine conditional statements:

R Logical Operators
Logical operators are used to combine conditional statements:

R Logical Operators

Logical operators are used to combine conditional statements:

 

Operator Description
& or && Element-wise Logical AND operator. Returns TRUE if both elements are TRUE
| or || Elementwise- Logical OR operator. Returns TRUE if one of the statement is TRUE
! Logical NOT – returns FALSE if statement is TRUE

Logical Operator Examples

is_sunny <- TRUE
is_warm <- FALSE

# Negation
not_sunny <- !is_sunny

# Logical AND
both_sunny_and_warm <- is_sunny & is_warm

# Logical OR
either_sunny_or_warm <- is_sunny | is_warm

Comparison Operators

<, >, <=, >=, ==, !=
Comparison operators are used to compare values.

p <- 10
q <- 5

# Less than
less_than <- p < q

# Greater than
greater_than <- p > q

# Less than or equal to
less_than_equal <- p <= q

# Greater than or equal to
greater_than_equal <- p >= q

# Equal to
equal_to <- p == q

# Not equal to
not_equal_to <- p != q

 

Membership Operators

%in%
The %in% operator checks if an element is present in a vector.

fruits <- c("apple", "banana", "cherry")

# Check if “banana” is in the vector
is_banana_present <- “banana” %in% fruits

Concatenation Operators

c()
The c() operator is used to concatenate vectors.

first_vector <- c(1, 2, 3)
second_vector <- c(4, 5, 6)

# Concatenate the vectors
combined_vector <- c(first_vector, second_vector)

Leave a Comment

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

Scroll to Top