Chapter 4 Control Flow
R is primarily a functional language, so you often don’t need control flow yourself. But if you want to, go for it. If you can write some quick code with a for loop, go for it! Tell the R bullies to fuck off. Do what feels comfortable to you.
4.1 If
Simple if
= TRUE
a if (a)
print("a is TRUE")
#> [1] "a is TRUE"
# conditionally run multiple expressions
if (a) {
print("a is TRUE")
print("a is TRUE")
}
#> [1] "a is TRUE"
#> [1] "a is TRUE"
If Else
= 5
x = 8
y if (x > y) {
print("x is greater than y")
else {
} print("x is less than or equal to y")
}
#> [1] "x is less than or equal to y"
The ifelse
function is the way to handle vector operations. It is like a vectorized version of ? :
in C or javascript.
= 1:10
x ifelse(x %% 2 == 0, "even", "odd")
#> [1] "odd" "even" "odd" "even" "odd" "even" "odd" "even" "odd" "even"
4.2 While
= runif(1)
x while (x < 0.95) {
= runif(1)
x }
4.3 For
For works like foreach in other languages.
= runif(100, 1, 100)
a for (x in a) {
if (x > 95)
print(x)
}
#> [1] 97.59641
#> [1] 97.67089
#> [1] 95.54705