R While Loop

The while loop repeats a block of statements for as long as a given condition stays true, which makes it the right tool when you don't know in advance exactly how many times you need to repeat something.

The basic syntax

A while loop starts with the keyword while, followed by a condition in parentheses, followed by the body of the loop wrapped in curly braces. Before every single pass through the body, R checks the condition. If it evaluates to TRUE, the body runs and then R checks the condition again. As soon as the condition evaluates to FALSE, the loop stops and R moves on to the code that follows it.

Example

count <- 1
while (count <= 5) {
  print(count)
  count <- count + 1
}

In this example, count starts at 1. Each time through the loop, R prints the current value and then increases count by one. Once count reaches 6, the condition count <= 5 becomes FALSE, so the loop stops, having printed the numbers 1 through 5.

Avoiding infinite loops

Note: A while loop only stops when its condition becomes FALSE. If the loop body never changes the variable that the condition depends on, the condition stays TRUE forever and the loop runs endlessly. Always double-check that something inside the loop moves you closer to the stopping condition.

for loops are great when you already know how many times to repeat something, but a while loop shines when the number of repetitions depends on the data itself, such as when you keep transforming a value until it crosses some threshold.

Halving Example

value <- 100
steps <- 0
while (value >= 1) {
  value <- value / 2
  steps <- steps + 1
}
cat("It took", steps, "halvings to get below 1\n")
  • Repeating a calculation until the result is 'close enough' to a target value
  • Simulating a process, such as compound interest, until a balance passes a goal
  • Retrying an action until it succeeds or a maximum attempt count is reached
  • Processing values one at a time until a stop signal appears in the data

Combining multiple conditions

Combined Condition

balance <- 1000
years <- 0
while (balance < 2000 && years < 50) {
  balance <- balance * 1.05
  years <- years + 1
}
cat("Balance passed 2000 after", years, "years\n")
Note: You can combine several checks with && (and) or || (or) inside the condition of a while loop. This is useful as a safety net, for example stopping a loop either when a goal is reached or when a maximum number of attempts has been used, whichever comes first.