Operations

Operations in R
Author

Mugabi Trevor .L

Published

2024-09-03

Keywords

Assigment Operator, Logical operator, Arithmetic operator, Comparison operator

Types of Operations

The types of operations in R can be broken down into these below: 1. Assignment Operators 1. Arithmetic Operators 1. Comparison Operators 1. Logical Operators 1. Identity Operators 1. Membership Operators

Lets Explore one by one below to see exactly what each is all about and some examples along the way.

1. Assignment Operators

Assignment operators in programming are used to assign values to variables. These operators store a value on the right side of the operator into the variable on the left side. In most programming languages, assignment operators not only assign values but also can perform arithmetic operations and then assign the result to a variable.

Types of Assignment Operators

  1. Simple Assignment (=): Assigns a value to a variable (e.g., a = 5).
  2. Assignment with (<-): Assigns a value to a variable (e.g., a <- 5).
# Simple Assignment using (<-).
num <- 20 
print(num)
[1] 20
# Assignment using (=).
num_1 = 25 # or num = 20 This will work in R
print(num_1)
[1] 25

NB: If you coming from another Programming language. its time to let you know that R doesnt have short hand syntax support so we can not use syntax like num = 1 then num +=1

2. Arithmetic Operators

Arithmetic operations in programming and mathematics involve performing basic calculations on numerical values. These operations are fundamental to many algorithms and data manipulations. Here’s a detailed definition and explanation of each.

Type of arithmetic operation

Arithmetic Operations: 1. Addition (+): Combines two values (e.g., a + b). 1. Subtraction (-): Subtracts one value from another (e.g., a - b). 1. **Multiplication (*): Multiplies two values (e.g., a * b). 1. Division (/): Divides one value by another (e.g., a / b). 1. Modulus (%%): Returns the remainder of division (e.g., a % b). 1. Exponentiation (^): Raises a value to the power of another (e.g., a b).

# Addition.
50 + 100
150
# Subtraction.
50 - 100
-50
# Multiplication (*).
50 * 100
5000
# Divison (/).
100 / 50
2
# Modulus -- For modulus in R we use two percent signs (%%).
100 %% 50
0
# Exponential (^).
50 ^ 100
7.88860905221012e+169

3. Comparison Operators

Comparison operators in programming are used to compare two values or expressions. These operators return a logical value (TRUE or FALSE) depending on whether the comparison is true or false. They are fundamental in decision-making structures like if statements, loops, and other control flow mechanisms.

Types of comparison Operators.

  1. Equal to (==): Checks if two values are equal (e.g., a == b).
  2. Not equal to (!=): Checks if two values are not equal (e.g., a != b).
  3. Greater than (>): Checks if one value is greater than another (e.g., a > b).
  4. Less than (<): Checks if one value is less than another (e.g., a < b).
  5. Greater than or equal to (>=): Checks if one value is greater than or equal to another (e.g., a >= b).
  6. Less than or equal to (<=): Checks if one value is less than or equal to another (e.g., a <= b).
# Equal to (==).
50 == 50  # Output TRUE
TRUE
# Not Equal to (!=).
50 != 50 # Output FALSE
FALSE
# Greater than (>).
100 > 4 # Output TRUE
TRUE
# Less than (<).
100 < 4 # Output FALSE
FALSE
# Greater than or equal to (>=):
50 >= 49 # Output TRUE
TRUE
# Less than or equal to (<=)
49 <= 100 # Output TRUE
TRUE

4. Logical Operators

Logical operators are used in programming to perform logical operations, typically on boolean values (TRUE or FALSE). These operators are essential for decision-making and control flow in code, allowing you to combine and evaluate conditions.

Types of Logical Operators

  1. AND (&& or and): Returns true if both conditions are true (e.g., a && b or a and b).
  2. OR (|| or or): Returns true if at least one condition is true (e.g., a || b or a or b).
  3. NOT (! or not): Returns true if the condition is false (e.g., !a or not a).
# AND  using single (&)
(5 > 2) & (5 > 4) # Output True if both conditions are true.
TRUE
# AND using  double (&&)
(5 > 2) && (5 > 4) # Output True if both conditions are true.
TRUE
# OR using single (|)
(5 > 2) | (5 < 2) # Output True if at least one condition is true.
TRUE
# OR using double (||)
(5 > 2) || (5 < 2) # Output True if at least one condition is true.
TRUE
# NOT (! or not)
!TRUE   # Result: FALSE
!FALSE  # Result: TRUE

!c(TRUE, FALSE, TRUE)  # Result: FALSE TRUE FALSE
FALSE
TRUE
  1. FALSE
  2. TRUE
  3. FALSE

Identity Operators

In R, identity operators are used to test if two objects are the same object or have the same identity. This concept is different from equality operators, which test if two objects are equivalent in value. Identity operators are particularly useful for checking if two variables point to the same object in memory, which is more about object identity rather than object equality. ### Types of Identity Operators 1. Identical() Function: Tests if two R objects are exactly the same, both in terms of their value and attributes. It checks for identity, meaning that the two objects are considered the same if they have the same type, structure, and content.

  1. is() Function: Checks if an object is of a specified class. It’s more about checking the identity of an object’s class rather than its value.
# using identical(x, y)
x <- c(1, 2, 3) 
y <- c(1, 2, 3)
z <- x

identical(x, y)  # FALSE, because x and y are not the same object in memory
identical(x, z)  # TRUE, because x and z are the same object in memory
TRUE
TRUE
# using is(x, class)
x <- 5
is(x, "numeric")  # TRUE, because x is a numeric object
is(x, "integer")  # FALSE, because x is not an integer
TRUE
FALSE

Membership Operators

In R, membership operators are used to test if elements belong to a specific set or structure. They are useful for checking whether values are present within vectors, lists, or other data structures. Here are the main membership operators in R:

  1. %in% Operator: Tests if elements of one vector are present in another vector. This operator is used to check membership within a set.

  2. match() Function: Finds the positions of the first matches of a vector of elements in another vector. It returns the index positions where matches are found, or NA if no match is found.

  3. %in% vs. match(): %in% Operator: Checks if elements are present in a set and returns a logical vector. match() Function: Provides the position of the matches or NA if no match is found.

Summary: %in% is used for membership testing, checking if elements are present in a set, and returns a logical vector and match() is used to find the index positions of matches and returns those positions or NA.

Both operators and functions are essential for data manipulation and querying in R, allowing you to efficiently handle and analyze your data.

# Using %in%.
# Defining  vectors.
fruits <- c("apple", "banana", "cherry")
my_fruit <- "banana"
my_fruits <- c("apple", "orange")

# Checking if `my_fruit` is in `fruits`
my_fruit %in% fruits  # TRUE

# Checking if elements in `my_fruits` are in `fruits`
my_fruits %in% fruits  # TRUE FALSE
# Here, "banana" is in the fruits vector, so the result is TRUE. The vector my_fruits
# contains "apple" (which is in fruits) and "orange" (which is not), so the result is TRUE FALSE.
TRUE
  1. TRUE
  2. FALSE
# Using match(x, table)
# Defining  vectors
fruits <- c("apple", "banana", "cherry")
my_fruits <- c("banana", "cherry", "orange")

# Find positions of `my_fruits` in `fruits`
match(my_fruits, fruits)  # 2 3 NA

#Here, "banana" is the 2nd element in fruits, 
#"cherry" is the 3rd, and "orange" is not found, so it returns NA.
  1. 2
  2. 3
  3. <NA>

Exercise

Description: This exercise will help you practice using logical operators in R to evaluate conditions and filter data based on multiple criteria. You will be working directly with vectors and logical statements.

  1. Problem 1:
    • Given an integer x=10 , perform the following checks:
    • Is x positive?
    • Use x > 0 to check if x is positive.
    • Is x even?
    • Use x %% 2 == 0 to check if x is even.
    • Is x divisible by 3?
    • Use x %% 3 == 0 to check if x is divisible by 3.
    • Is x greater than 10 and less than 50?
    • Use x > 10 & x < 50 to check if x is within this range.
    • Is x either less than 0 or greater than 100?
    • Use x < 0 | x > 100 to check this condition.
  2. Problem 2:
    • Given two integers x and y, evaluate the following conditions: x <- 12, y <- -8

    • Are both x and y positive?

    • Use x > 0 & y > 0 to check if both are positive.

    • Is at least one of x or y negative?

    • Use x < 0 | y < 0 to check if at least one is negative.

    • Are both x and y even?

    • Use (x %% 2 == 0) & (y %% 2 == 0) to check if both are even.

    • Is at least one of x or y odd?

    • Use (x %% 2 != 0) | (y %% 2 != 0) to check if at least one is odd.

  3. Problem 3:
    • Filter this Vector Based on Logical Conditions, vec <- c(3, 12, -5, 20, 7, 18, -2, 30)
    • Given a numeric vector vec, filter out and print the elements that satisfy the following conditions:
      • The element is positive.
      • The element is even.
      • The element is greater than or equal to 10.

Run each block of code in R. Understand how logical operators are used to evaluate and filter data based on multiple conditions. This exercise will help you gain a solid understanding of logical operators in R by applying them directly to vectors and conditions.