concept condition in category R

appears as: condition, The condition, The condition, conditions, condition, conditions
Beyond Spreadsheets with R

This is an excerpt from Manning's book Beyond Spreadsheets with R.

You can evaluate this with a “large” value (less than 10 is the condition required to avoid the error; execution will stop if the condition is not true):

If the condition never evaluates to TRUE, then the body is never executed:

while (1 == 2) {
  print("this line will not be printed")
}

The condition in the while statement needs to be valid, which means that any variables it depends on need to already exist. One way to deal with this is to be explicit about the first value by initializing it outside of the while statement. Within the body of the loop, the variable(s) can (and should) be updated. Here’s a simple while loop that prints the current value of i on each iteration and then increases it by 1 until it is no longer less than 3:

i <- 0    #1  
while (i < 3) {    #2  
  print(i)    #3  
  i <- i + 1    #4  
}
#> [1] 0
#> [1] 1
#> [1] 2

#1   Initializes i to 0
#2   The condition of the loop is that i is less than 3, which it is to begin with.
#3   On each iteration, the value of i is printed.
#4   At the end of each iteration, i is increased by 1.