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:
conditionis usually a logical statement.true_code_1,true_code_2, etc., are the code blocks executed whenconditionevaluates toTRUE.false_code_1,false_code_2, etc., are the code blocks executed whenconditionevaluates toFALSE.
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:
11.1.3 Using ifelse()
The ifelse() function allows you to select values based on whether a condition is TRUE or FALSE:
Here, ifelse() evaluates x %% 2 == 0 and assigns "even" if TRUE and "odd" otherwise.
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:
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] TRUE11.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 foundFor ||, 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 foundHere, FALSE && stops evaluation immediately, as the result is already determined. In contrast, & attempts full evaluation and fails.
11.1.7 Exercises
- Checking Positive, Negative, or Zero
Write an if-else statement that checks whether a given number y is:
- Positive,
- Negative, or
- Zero.
Print an appropriate message for each case.
Example Input:
Expected Output:
"y is a negative number."
- 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:
Expected Output:
"Your grade is B."
- 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:
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:
Expected Output:
"The largest number is 15."