Chapter 7 Multiple condition decisions

While simple if and if else operations tests single conditions, we can make more complex operations, which tests multiple conditions.

With the ifelse() function, we can test a test a vector of conditions and/or apply functions only under certain conditions. See the examples below:

a <- 1:10

ifelse(test = a > 5, yes = "yes", no = "no")
##  [1] "no"  "no"  "no"  "no" 
##  [5] "no"  "yes" "yes" "yes"
##  [9] "yes" "yes"
a <- (-4):5

sqrt(ifelse(test = a >= 0, yes = a, no = NA))
##  [1]       NA       NA
##  [3]       NA       NA
##  [5] 0.000000 1.000000
##  [7] 1.414214 1.732051
##  [9] 2.000000 2.236068

While the if() and if() else statements leave you with exactly two options, nested if() else statement allows you consider more alternatives.

if (test_expression1) {
    statement1
} else if (test_expression2) {
    statement2
} else if (test_expression3) {
    statement3
} else {
    statement4
}