If-then-else
If-then-else statements select which code to run based on a condition. The simplest form is:
a <- 5.0
b <- 10.0
if (a < b) {
print("a is smaller than b")
}
## [1] "a is smaller than b"
An if statement can be extended with else if branches and an optional final else branch. In this example, a more specific condition is checked first:
if (a < b/2) {
print("a is much smaller than b")
} else if (a < b) {
print("a is smaller than b")
} else if (a == b) {
print("a equals b")
}
## [1] "a is smaller than b"
Conditions are checked in order. The first condition that is TRUE selects its branch; later branches are skipped. If none is TRUE, the final else branch runs, if present.
The example prints nothing when a is larger than b, because none of its conditions is TRUE. Add a final else branch to handle that case:
a <- 15.0
b <- 10.0
if (a < b/2) {
print("a is much smaller than b")
} else if (a < b) {
print("a is smaller than b")
} else if (a == b) {
print("a equals b")
} else {
print("a is larger than b.")
}
## [1] "a is larger than b."
You can combine comparisons with logical operators:
c <- 20.0
if (a < b & a == c) {
print("a is smaller than b and equal to c")
} else if (a > b & a == c) {
print("a is larger than b and equal to c")
} else {
print("a non-equal to c.")
}
## [1] "a non-equal to c."
An if branch runs when its condition is TRUE. You can also test whether a stored logical value is FALSE:
test <- a < b
if (test == FALSE) {
print("a is larger than b")
} else {
print("a is smaller than or equal b.")
}
## [1] "a is larger than b"
If-then-else decisions are useful if your computation needs different workflows for different variable values.
# Pseudocode
if("<some logical (and boolean) expression>"){
"<do something>"
} else {
"<do something else>"
}