Chapter 8 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:
<- 1:10
a
ifelse(test = a > 5, yes = "yes", no = "no")
## [1] "no" "no" "no" "no"
## [5] "no" "yes" "yes" "yes"
## [9] "yes" "yes"
<- (-4):5
a
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) {
statement1else if (test_expression2) {
}
statement2else if (test_expression3) {
}
statement3else {
}
statement4 }