5.3 Loops

  • Iteration over a elements of a vector

for (item in vector) perform_action

First example

for(i in 1:5) {
  print(1:i)
}
#> [1] 1
#> [1] 1 2
#> [1] 1 2 3
#> [1] 1 2 3 4
#> [1] 1 2 3 4 5

x <- numeric(length=5L)
df <- data.frame(x=1:5)

for(i in 1:5) {
  df$y[[i]] <- i+1
}

Second example: terminate a for loop earlier

  • next skips rest of current iteration
  • break exits the loop entirely
for (i in 1:10) {
  if (i < 3) 
    next

  print(i)
  
  if (i >= 5)
    break
}
#> [1] 3
#> [1] 4
#> [1] 5