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

a = TRUE
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

x = 5
y = 8
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.

x = 1:10
ifelse(x %% 2 == 0, "even", "odd")
#>  [1] "odd"  "even" "odd"  "even" "odd"  "even" "odd"  "even" "odd"  "even"

4.2 While

x = runif(1)
while (x < 0.95) {
  x = runif(1)
}

4.3 For

For works like foreach in other languages.

a = runif(100, 1, 100)
for (x in a) {
  if (x > 95)
    print(x)
}
#> [1] 97.59641
#> [1] 97.67089
#> [1] 95.54705