## 11.3 Essentials of conditionals

Whereas most of our scripts so far relied on being executed linearly (in a top-down, left-to-right, line-by-line fashion), using functions implies jumping around in large amounts of code. Strictly speaking, we have also been using statements that were parsed from right to left (e.g., assignments like x <- 1) or bottom-to-top (e.g., when assigning a multi-line pipe of dplyr statements to an object). Also, given that we have been using functions all along, we really have been jumping around in base R code since our very first session.

This section addresses a special type of flow control: When thinking about the flow of information through a program (which can be a single R function, or an entire system of R packages), we often come to junctions at which we want to say: Based on some criterion being met, we either want to do this, or, if the criterion is not met, do something else. Such junctions are an important feature of any programming language and are typically handled by special functions, special control structures, or conditionals (i.e., “if-then” or “if-then-else” statements).

### 11.3.1 Flow control

Creating functions often requires controlling the flow of information within the body of a function. We can distinguish between several ways how this can be achieved:

• Special functions (e.g., like return, print, or stop) can cause side-effects or skip code (e.g., by exiting the function).

• Functions often incorporate iteration and loops, which are covered in the next chapter (i.e., Chapter 12 on Iteration).

• Testing input arguments or distinguishing between several cases requires the conditional execution of code, discussed in this section. In the definition of describe() above, we have seen that functions frequently require checking some properties of its inputs, distinguishing between cases, and controlling the flow of data processing based on test results. This is the job of conditional statements, which exist in many different forms. In this section, we only cover the most essential types.

### 11.3.2 If-then

A conditional statement conducts a test (which evaluates to either TRUE or FALSE) and executes additional code based on the value of the test. The simplest conditional in R is the if function, which implements the logic of if-then in the following if (test) {...} structure:

if (test) {    # if: test is TRUE
print("ok")  # then: print ok
}

Here, test must evaluate to a single Boolean value (i.e., either TRUE or FALSE). If test is TRUE the code in the subsequent {...} is executed (here: "ok" is printed to the Console) – otherwise the code in the subsequent {...} is skipped, as if it was not there or commented out:

x <- 101
if (x >= 100) { print(paste0("The number ", x, " is big.")) }
#> [1] "The number 101 is big."

x <- 99
if (x >= 100) { print(paste0("The number ", x, " is big.")) }
# Note that nothing happens here! 

Note that if test is a Boolean value, we do not need to ask for the condition test == TRUE.

### 11.3.3 If-then-else

If a test fails, we often want something else to happen. To accommodate this desire, a slightly more complicated form of if statement includes an additional {...} after an else statement:

if (test) {
print("case 1")  # if test is TRUE:  case 1
} else {
print("case 2")  # if test is FALSE: case 2
}

Here, the truth value of test determines whether the 1st or the 2nd {...} is executed. As test must be either TRUE or FALSE, we either see “case 1” printed (if test is TRUE) or “case 2” printed (if test is FALSE).

The following sequence illustrates how tests work (and can fail to work):

# (a) test is TRUE:
person <- "daughter"
if (person == "daughter") {print("female")} else {print("male")}
#> [1] "female"

# (b) test is FALSE:
person <- "grandfather"
if (person == "daughter") {print("female")} else {print("male")}
#> [1] "male"

# But:
# (c) test is FALSE, but should be TRUE:
person <- "grandmother"
if (person == "daughter") {print("female")} else {print("male")}
#> [1] "male"

### 11.3.4 Vectorized ifelse

A crucial limitation of R’s basic if statement is that its test only assumes a single TRUE of FALSE as its output. However, when writing functions, we often want to make them work with vectors of input values, rather than a single input. Testing multiple values at once is possible with the ifelse(test, yes, no) function that uses vectorized test, yes, and no arguments (which are recycled to the same length):

v <- 1:5

ifelse(v %% 2 == 0, "even", "odd")
#> [1] "odd"  "even" "odd"  "even" "odd"
ifelse(v >= 3, TRUE, FALSE)
#> [1] FALSE FALSE  TRUE  TRUE  TRUE

Note that the yes, and no values used with ifelse should typically be of the same type, and NA values remain NA:

w <- c(1, NA, 3)
ifelse(w %% 2 == 0, "even", "odd")
#> [1] "odd" NA    "odd"

### 11.3.5 More complex tests

The condition test of a conditional statement can contain multiple tests. If so, each individual test must evaluate to either TRUE or FALSE and the different tests are linked with && or ||, which work like the logical connectors & and |, but are evaluated sequentially (from left to right):

if (test_1 || (test_2 && test_3)) {
print("case 1")
} else {
print("case 2")
}

#### Example

Here’s a way to fix our problem from above (i.e., evaluating “grandmother” as “male”) by implementing a more comprehensive test:

person <- "grandmother"

# (c) with a more complex test:
if (person == "daughter" || person == "mother" || person == "grandmother") {
print("female")
} else {
print("male")
}
#> [1] "female"

A vectorized version of this if-then-else statement can be written with ifelse(), but will still mis-classify anything not considered when designing the test (e.g., stepmothers, broomsticks, etc.):

person <- c("mother", "father", "daughter", "son", "grandmother",
"stepmother", "broomstick")

ifelse(person == "daughter" | person == "mother" | person == "grandmother",
"female", "male")
#> [1] "female" "male"   "female" "male"   "female" "male"   "male"

#### More cases

As we can replace any {...} in a conditional statement if (test) {...} else {...} by another conditional statement, we can distinguish more than 2 cases:

if (test_1) {        # if test_1 is TRUE:
print("case 1")    # then: case 1
} else if (test_2) { # if test_2 is TRUE:
print("case 2")    # then: case 2
} else {             # if NONE of the tests are TRUE:
print("else")      # then: else case
}

Here, 2 cases are contingent on their corresponding condition being TRUE, otherwise the final {...} is reached and "else" is being printed. Thus, an “else case” often serves as a generic case that occurs when none of the earlier tests are true.

Note that the following variant of this conditional is different:

if (test_1) {         # if test_1 is TRUE:
print("case 1")     # then: case 1
} else if (test_2) {  # if test_2 is TRUE:
print("case 2")     # then: case 2
} else if (test_3) {  # if NONE of the tests are TRUE, BUT test_3 is TRUE:
print("else")       # then: else case
}

Here, the final {...} is contingent on another test_3 being TRUE. Thus, the conditions that the final "else" is being printed are not only that test_1 and test_2 are both FALSE but also that test_3 is TRUE. If all 3 tests fail, none of the cases is reached and nothing is printed.

#### Note

• When a test evaluates to TRUE, the corresponding {...} is evaluated and any later instances of test and {...} are skipped. Thus, only a single case of {...} is evaluated, even if multiple tests would evaluate to TRUE.

### 11.3.6 Switch

A useful alternative to overly complicated if statements is switch, which selects one of a list of alternatives:

do_op <- function(x, y, op) {

switch(op,
plus = x + y,
minus = x - y,
times = x * y,
divide = x / y,
power = x ^ y,
stop("Unknown operation!")
)
}

# Check:
do_op(3, 2, "plus")
#> [1] 5
do_op(3, 2, "minus")
#> [1] 1
do_op(3, 2, "power")
#> [1] 9

# But:
# do_op(3, 2, "square_root")  # would reach stop (and yield an Error)

Here, op was specified as a character variable. If switch is used with a numeric expression i, it selects the i-th case (with i being coerced into an integer). For example:

get_i <- function(v, i = 1) {

switch(i,
v[1],
v[2],
v[3],
stop("Unknown case of i!")
)
}

# Check:
v <- 11:15
get_i(v)
#> [1] 11
get_i(v, 2)
#> [1] 12
get_i(v, 3)
#> [1] 13

## But:
# get_i(v, 4)  # would reach stop (and yield an Error)

#### Practice

Let’s practice what we have learned about conditionals in R.

##### A conditional nursery rhyme

Consider the following check_flow function:

check_flow <- function(n) {
if (is.logical(n)) {return("Logo!")} else
{print("Ok:")}
if (length(n) == 1 && is.numeric(n))
{switch(n,print("ene"),print("mene"),print("miste"),
print("es rappelt"),print("in der kiste"))
} else if (is.character(n)) {
if (is.character(n)) {n <- tolower(n)}
switch(n,"a" = return("ene"),
"b" = return("mene"),"c" = return("mu"))
} else {return("Raus bist du!")}
"(etc.)"}

The function appears to implement some nursery rhyme, but is really messy, unfortunately.51 Hence, we need to clean up this code before we can even begin with trying to understand the function.

1. Format the function so that it becomes easier to read and parse.

A possible solution would indent commands, place any } on a new line, and generally introduce lots of white space, as follows:

check_flow <- function(n) {

if (is.logical(n)) {
return("Logo!")
} else {
print("Ok:")
}

if (length(n) == 1 && is.numeric(n)) {

switch(n,
print("ene"),
print("mene"),
print("miste"),
print("es rappelt"),
print("in der kiste")
)

} else if (is.character(n)) {

if (is.character(n)) {n <- tolower(n)}

switch(n,
"a" = return("ene"),
"b" = return("mene"),
"c" = return("mu")
)

} else {

return("Raus bist du!")
}

"(etc.)"
}
1. Describe and try to understand this function. What does it do and how does it do it?

2. Answer and predict the results of the following questions:

• Which cases does the 1st conditional statement distinguish?
• When is the 1st switch statement reached? When is the 2nd switch statement reached?
• What is the difference between the print and the return statements?
• Under which conditions does the function return "raus bist du"?
• What happens when you call check_flow() or check_flow(NA)?
1. Test your predictions by evaluating the following calls of the check_flow() function:
# Check:
check_flow(2 < 1)
check_flow(2)
check_flow(4)
check_flow(6)
check_flow(8)
check_flow("A")
check_flow("C")
check_flow("ABC")

# Note:
check_flow()  # yields ERROR: argument "n" missing, with no default
check_flow(NA)
check_flow(sqrt(2))
check_flow(pi)
check_flow(4.1)
check_flow(c(1, 2))
check_flow(c("A", "B")) # yields ERROR in switch: EXPR must be a length 1 vector

1. Actually, this example illustrates pretty well how the functions of students tend to look when they first start writing functions. Imagine searching for a typo in code formatted like this…