11.1 Conditional Statements via if, else, and switch()

Conditional statements are a type of control statement that execute specific blocks of code depending on the value of a condition.

11.1.1 The Structure of Conditional Statements

The general structure of a simple conditional statement is:

if (condition) {
    true_code_1
    true_code_2
} else {
    false_code_1
    false_code_2
    false_code_3
}
  • condition is usually a logical statement.
  • true_code_1, true_code_2, etc., are the code blocks executed when condition evaluates to TRUE.
  • false_code_1, false_code_2, etc., are the code blocks executed when condition evaluates to FALSE.

The else block is optional.

11.1.2 Example: Checking Even or Odd Numbers

Let’s check whether a number x is even or odd and print the corresponding message:

x <- 3
if (x%%2 == 0) {
    cat("x is an even number\n")
} else {
    cat("x is an odd number\n")
}
#> x is an odd number

11.1.3 Using ifelse()

The ifelse() function allows you to select values based on whether a condition is TRUE or FALSE:

x_type <- ifelse(x%%2 == 0, "even", "odd")
x_type
#> [1] "odd"

Here, ifelse() evaluates x %% 2 == 0 and assigns "even" if TRUE and "odd" otherwise.

11.1.4 Multiple Conditions with else if

You can chain multiple conditions using else if:

x <- 9
if (x%%3 == 1) {
    cat("The remainder of x divided by 3 is 1.\n")
} else if (x%%3 == 2) {
    cat("The remainder of x divided by 3 is 2.\n")
} else {
    cat("x is divisible by 3.\n")
}
#> x is divisible by 3.

11.1.5 Using switch() for Multiple Choices

The switch() function selects and returns a value based on an expression.

11.1.5.1 Numeric Indexing

If the first argument is an integer, switch() returns the value corresponding to the indexed position:

switch(2, "sheep", "pig", "monkey")  # Returns 'pig'
#> [1] "pig"
switch(4, "sheep", "pig", "monkey")  # Returns nothing

11.1.5.2 Character Matching

If the first argument is a character, switch() matches it to the names of the elements:

switch("pig", sheep = 2, pig = 3, monkey = 4)  # Returns 3
#> [1] 3
switch("pi", sheep = 2, pig = 3, monkey = 4)  # Returns NULL (no match)
switch("monkey", sheep = 2, pig = 3, monkey = "mona")  # Returns 'mona'
#> [1] "mona"

11.1.6 Logical Operators in Conditional Statements

Logical operators like & (AND) and | (OR) work element-wise on logical vectors. However, in if statements, their counterparts && and || are typically used:

  • && (AND): Checks only the first element of the logical vectors and stops evaluation as soon as the result is determined.
  • || (OR): Similarly checks only the first element and short-circuits evaluation when the result is determined.

11.1.6.1 Example: Comparing Operators

logi_1 <- c(TRUE, FALSE, TRUE, FALSE)
logi_2 <- c(FALSE, TRUE, TRUE, FALSE)

# Element-wise operations
logi_1 & logi_2  # Returns c(FALSE, FALSE, TRUE, FALSE)
#> [1] FALSE FALSE  TRUE FALSE
logi_1 | logi_2  # Returns c(TRUE, TRUE, TRUE, FALSE)
#> [1]  TRUE  TRUE  TRUE FALSE

# First-element-only operations
logi_1 && logi_2  # Returns FALSE
#> [1] FALSE
logi_1 || logi_2  # Returns TRUE
#> [1] TRUE

11.1.6.2 Short-Circuit Evaluation

Short-circuit evaluation with && and || avoids unnecessary computation. Consider the following example:

undefined_object  # Throws an error
#> Error in eval(expr, envir, enclos): object 'undefined_object' not found
TRUE || undefined_object  # Returns TRUE
#> [1] TRUE
TRUE | undefined_object  # Throws an error
#> Error in eval(expr, envir, enclos): object 'undefined_object' not found

For ||, since TRUE || guarantees a TRUE result, the evaluation stops early without checking undefined_object.

11.1.6.3 Another Example: AND Operator

FALSE && undefined_object  # Returns FALSE
#> [1] FALSE
FALSE & undefined_object  # Throws an error
#> Error in eval(expr, envir, enclos): object 'undefined_object' not found

Here, FALSE && stops evaluation immediately, as the result is already determined. In contrast, & attempts full evaluation and fails.

11.1.7 Exercises

  1. Checking Positive, Negative, or Zero

Write an if-else statement that checks whether a given number y is:

  1. Positive,
  2. Negative, or
  3. Zero.

Print an appropriate message for each case.

Example Input:

y <- -5

Expected Output:

"y is a negative number."
  1. Determine the Grade

Create a program that uses if, else if, and else to assign a grade based on a student’s score. Use the following grading scheme:

  • A: 90 and above
  • B: 80-89
  • C: 70-79
  • D: 60-69
  • F: Below 60

Example Input:

score <- 85

Expected Output:

"Your grade is B."
  1. Choose a Pet Using switch()

Use the switch() function to match an input string to a pet and return its description. For example:

  • "dog": “Dogs are loyal and friendly.”
  • "cat": “Cats are independent and curious.”
  • "fish": “Fish are calming and easy to care for.”
  • Default case: “Pet type not recognized.”

Example Input:

pet <- "cat"

Expected Output:

"Cats are independent and curious."

4.Maximum of Three Numbers

Write a program that uses nested if-else statements to find the largest of three numbers, a, b, and c.

Example Input:

a <- 7
b <- 15
c <- 10

Expected Output:

"The largest number is 15."