2024

Introduction to Conditional Statements

Conditional statements allow R programs to execute different blocks of code based on certain conditions.

The if Statement

Basic Syntax

if (condition) {
  # code to execute if condition is True
}

The if Statement

Example

x <- 10
if (x > 5) {
  print("x is greater than 5")
}
## [1] "x is greater than 5"
  • Executes the print statement because the condition (x > 5) is True.

The else Statement

Extending if with else

if (condition) {
  # code if condition is True
} else {
  # code if condition is False
}

The else Statement

Example

x <- 3
if (x > 5) {
  print("x is greater than 5")
} else {
  print("x is not greater than 5")
}
## [1] "x is not greater than 5"
  • Executes the second print statement because the condition is False.

The else if Statement

For Multiple Conditions

if (condition1) {
  # code if condition1 is True
} else if (condition2) {
  # code if condition2 is True
} else {
  # code if neither condition is True
}

The else if Statement

Example

x <- 5
if (x > 5) {
  print("x is greater than 5")
} else if (x == 5) {
  print("x is equal to 5")
} else {
  print("x is less than 5")
}
## [1] "x is equal to 5"
  • Executes the print statement in the else if block.

Utilizing the any Function in R

The any function is a logical operation in R that tests if any of the elements in a given vector or data structure are TRUE.

Example

values <- c(TRUE, FALSE, FALSE)
result <- any(values)
print(result) # Output: TRUE
## [1] TRUE

Utilizing the all Function in R

The all function is a logical operation in R that tests if all of the elements in a given vector or data structure are TRUE.

Example

values <- c(TRUE, FALSE, FALSE)
result <- all(values)
print(result) # Output: FALSE
## [1] FALSE

The ifelse Function

ifelse(test_expression, yes, no)
  • The ifelse function is a vectorized conditional function which evaluates each element of the test_expression.

  • If the condition for an element is TRUE, it returns the corresponding element from yes; otherwise, it returns the corresponding element from no.

The ifelse Function

Example

x <- 5
result <- ifelse(x > 10, "Greater than 10", "Less or equal to 10")
print(result)
## [1] "Less or equal to 10"
  • Returns a character vector: "Less or equal to 10".

ifelse can operate on vectors

Example

x <- c(5, 10, 15)
result <- ifelse(x > 10, "Greater than 10", "Less or equal to 10")
print(result)
## [1] "Less or equal to 10" "Less or equal to 10" "Greater than 10"
  • Returns a character vector: ["Less or equal to 10", "Less or equal to 10", "Greater than 10"].

Considerations When Using ifelse

  • Type Coercion: The yes and no arguments must be the same type, or they will be coerced to a common type, which might not be intended.
x <- c(5, 10, 15)
result <- ifelse(x > 10, x, "Less or equal to 10")
print(result)
## [1] "Less or equal to 10" "Less or equal to 10" "15"
  • Returns a character vector: ["Less or equal to 10", "Less or equal to 10", "15"].

  • Last element is coerced to character.

Introduction to Loops

Loops in R are used to execute a block of code repeatedly.

The for Loop

Iterating Over Sequences

for (element in sequence) {
  # code to execute for each element
}

The for Loop

Example

fruits <- c("apple", "banana", "cherry")
for (fruit in fruits) {
  print(fruit)
}
## [1] "apple"
## [1] "banana"
## [1] "cherry"
  • Prints each fruit in the vector.

The for Loop

Example

# Print numbers 1 through 5
for(i in 1:5) {
  print(i)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
  • Prints the numbers 1 through 5.

The while Loop

Repeating While a Condition is True

while (condition) {
  # code to execute while condition is True
}

The while Loop

Example

# Print numbers 1 through 5
i <- 1
while(i <= 5) {
  print(i)
  i <- i + 1
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
  • Continues to execute as long as the condition is TRUE.

Question 1

What does the following code print?

if (FALSE) {
  print("False!")
} else if (TRUE) {
  print("Now True!")
} else {
  print("Finally True!")
}
## [1] "Now True!"
  1. False!
  2. Now True!
  3. Finally True!
  4. Nothing

Answer 1

Click here for the answer
  • The correct answer is 2. Now True!. The else if block is executed because its condition is True.

Question 2

How many times does the following loop run?

x <- 3
while (x < 8) {
  print("Looping!")
  x <- x + 2
}
## [1] "Looping!"
## [1] "Looping!"
## [1] "Looping!"
  1. 2 times
  2. 3 times
  3. 4 times
  4. 5 times

Answer 2

Click here for the answer
  • The correct answer is 2. 3 times. The loop increments x by 2 each time, starting from 3 and stopping before it reaches 8.

Question 3

Consider the following code:

numbers <- c(1, 4, 7, 10) # Initial vector of numbers
target <- 5               # Target value
i <- 1                    # Index to traverse the vector

while(any(numbers != target)) {

  i <- ifelse(numbers[i]==target, i + 1, i)

  numbers[i] <- ifelse(numbers[i] < target, 
                       numbers[i] + 1, 
                       numbers[i] - 1)

  print(numbers)
}

What will be the final state of the numbers vector after the loop terminates?

  1. c(5, 5, 5, 5)
  2. c(2, 5, 8, 11)
  3. The loop will not terminate and result in an infinite loop.
  4. c(1, 4, 7, 10)

Answer 3

Click here for the answer
  • The correct answer is 1. c(5, 5, 5, 5). The script uses the ifelse statement to adjust each element towards the target value by either incrementing or decrementing. The loop iterates to the next element only when numbers[i] has reached the target value. Thus ensuring the loop will terminate when all numbers become equal to the target value of 5.

Question 4

What will the following code output?

for(i in c(1, 3, 5)) {
  if(i %% 2 == 0) {
    print("Even")
  } else {
    print("Odd")
  }
}
  1. Even Odd Even
  2. Odd Odd Odd
  3. Even Even Even
  4. Odd Even Odd

Answer 4

What will the following code output?

for(i in c(1, 3, 5)) {
  if(i %% 2 == 0) {
    print("Even")
  } else {
    print("Odd")
  }
}
Click here for the answer
  • The correct answer is 2. Odd Odd Odd. The loop iterates through a vector of odd numbers, and the conditional checks if the number is even (which it never is), so “Odd” is printed each time.