R For Loop


For Loops

A for loop is used for multiplication in sequence:

Example
for (x in 1:10) {
  print(x)
}

This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.

With a for loop we can create a set of statements, once per object in vector, matching members, lists, etc ..

Example

Print every item in a list:

fruits <- list("apple", "banana", "cherry")

for (x in fruits) {
  print(x)
}

Example

Print the number of dices:

dice <- c(1, 2, 3, 4, 5, 6)

for (x in dice) {
  print(x)
}

The for loop does not require variable indexing to be pre-configured, such as for while loops.



Break

With a break statement, we can stop the loop before it goes into all items:

Example

Stop the loop at "cherry":

fruits <- list("apple", "banana", "cherry")

for (x in fruits) {
  if (x == "cherry") {
    break
  }
  print(x)
}

The loop will stop at "cherry" because we chose to end the loop using a break statement where x is equal to "cherry" (x == "cherry").



Next

With the next statement, we can skip repeats without breaking the loop:

Example

Skip "banana":

fruits <- list("apple", "banana", "cherry")

for (x in fruits) {
  if (x == "banana") {
    next
  }
  print(x)
}

When the loop passes the "banana", it will jump and continue the loop.



Yahtzee!

If .. Else Combined with a For Loop

To illustrate a practical example, suppose we are playing a game of Yahtzee!

Example

Print "Yahtzee!" If the dice number is 6:

dice <- 1:6

for(x in dice) {
  if (x == 6) {
    print(paste("The dice number is", x, "Yahtzee!"))
  } else {
    print(paste("The dice number is", x, "Not Yahtzee"))
  }
}

When the loop reaches values ​​from 1 to 5, it prints "No Yahtzee" and its number. When it reaches a value of 6, it prints "Yahtzee!" and its number.



Nested Loops

You can also have a loop inside the loop:

Example

Print the adjective of each fruit in a list:

adj <- list("red", "big", "tasty")

fruits <- list("apple", "banana", "cherry")
  for (x in adj) {
    for (y in fruits) {
      print(paste(x, y))
  }
}