R While Loop with Programming Examples

โšก Smart Summary

While Loop in R Programming repeats a block of code for as long as its condition stays TRUE. The condition is tested before every pass, so the body may never run at all, and something inside it must eventually make the condition FALSE.

  • ๐Ÿ” Core Syntax: while (condition) { expression } tests the condition first and runs the body only while it evaluates to TRUE.
  • โš ๏ธ Termination Rule: A statement inside the body must change the condition, otherwise the loop never ends.
  • ๐Ÿ”ข Counter Pattern: Initialise a variable before the loop and increment it inside, which is the standard counting idiom.
  • ๐Ÿ›‘ Flow Control: break exits the loop immediately and next skips to the following iteration.
  • ๐Ÿ” repeat Alternative: repeat runs unconditionally and relies entirely on break, which suits do-while style logic.
  • ๐Ÿ“ When to Choose: Use while when the number of iterations is unknown in advance, and for when it is fixed.

While Loop in R

While Loop in R Programming

A while loop in R repeats a block of code for as long as its condition remains TRUE. The condition is tested before each pass, so a while loop can run zero times if the condition is FALSE from the start.

While Loop Syntax in R

Following is the syntax for While Loop in R programming:

while (condition) {
     Exp	
}

R While Loop Flowchart

R While Loop Flowchart
R While Loop Flowchart

Note: something inside the loop must eventually make the condition FALSE. If nothing does, the loop runs forever and you have to interrupt R with Esc or Ctrl+C.

while Loop vs for Loop vs repeat Loop in R

R offers three looping constructs, and choosing between them comes down to whether you know in advance how many iterations you need.

Criteria while for repeat
Iteration count Unknown in advance Known in advance Unknown in advance
Condition tested Before each pass Sequence is exhausted Never, you must call break
Minimum runs Zero Zero One
Typical use Converging on a threshold Walking a vector or list Do-while style logic
Syntax while (cond) { } for (i in v) { } repeat { … break }
# repeat always runs at least once
count <- 1
repeat {
    print(count)
    count <- count + 1
    if (count > 5) break
}

The stock example above is a natural fit for while: you cannot know beforehand how many random draws it will take before the price falls to 45.

While Loop in R: Examples

Example 1

Start with the simplest possible R programming example. You create a counter and add 1 to it on every pass. The loop must be able to end, so the condition explicitly tells R to stop once the variable passes 10.

Note: If you want to see current loop value, you need to wrap the variable inside the function print().

#Create a variable with value 1
begin <- 1

#Create the loop
while (begin <= 10){

#See which loop we are on
cat('This is loop number', begin, '\n')

#add 1 to the variable begin after each loop
begin <- begin+1
print(begin)
}

Output:

## This is loop number 1[1] 2
## This is loop number 2[1] 3
## This is loop number 3[1] 4
## This is loop number 4[1] 5
## This is loop number 5[1] 6
## This is loop number 6[1] 7
## This is loop number 7[1] 8
## This is loop number 8[1] 9
## This is loop number 9[1] 10
## This is loop number 10[1] 11

Example 2

Suppose you bought a stock at 50 dollars. If the price falls to 45 or below you want to short it, otherwise you keep holding. Each pass of the loop moves the price randomly by up to 10 in either direction around 50:

set.seed(123)
# Set variable stock and price
stock <- 50
price <- 50

# Loop variable counts the number of loops 
loop <- 1

# Set the while statement
while (price > 45){

# Create a random price between 40 and 60
price <- stock + sample(-10:10, 1)

# Count the number of loop
loop <- loop + 1

# Print the number of loop
print(loop)
}

Output:

## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
cat('it took',loop,'loop before we short the price. The lowest price is',price)

Output:

## it took 7 loop before we short the price. The lowest price is 40

How to Use break and next in a While Loop

Two keywords change the normal flow of any R loop.

  • break exits the loop immediately, skipping every remaining iteration.
  • next abandons only the current iteration and jumps straight to the next condition test.
# break: stop as soon as a condition is met
i <- 1
while (i <= 100) {
    if (i * i > 50) {
        cat('First square above 50 is', i * i, '\n')
        break
    }
    i <- i + 1
}

# next: skip the even numbers
i <- 0
while (i < 10) {
    i <- i + 1
    if (i %% 2 == 0) next
    print(i)
}

One trap worth knowing. In a while loop, next jumps back to the condition test without running anything below it. If your counter is incremented at the bottom of the body, next skips that increment and the loop hangs forever. That is why the second example increments before the next statement rather than after it.

Common While Loop Errors and Infinite Loops

Four mistakes account for almost every failed while loop.

  • The counter is never updated. Forgetting the increment leaves the condition permanently TRUE. Press Esc in RStudio, or Ctrl+C in a terminal, to interrupt.
  • The condition returns NA. If any value in the test is NA, R stops with “missing value where TRUE/FALSE needed”. Guard it with is.na() or with isTRUE().
  • The condition is longer than one element. Since R 4.2, a condition of length greater than one is an error rather than a warning. Wrap it in any() or all().
  • Floating-point comparison never becomes FALSE. while (x != 0.3) can loop forever because 0.1 + 0.2 is not exactly 0.3. Compare with a tolerance instead, using abs(x – 0.3) > 1e-8.
# Safety valve: cap the number of iterations
iter <- 0
while (price > 45 && iter < 1000) {
    price <- stock + sample(-10:10, 1)
    iter <- iter + 1
}

Adding a maximum iteration count is cheap insurance in any loop whose exit depends on random or external data.

FAQs

A while loop tests its condition before the first pass, so it can run zero times. A repeat loop has no condition and always runs at least once, exiting only when it reaches a break statement.

Press Esc in RStudio or Ctrl+C in a terminal to interrupt execution. Prevent the situation by ensuring some statement inside the body changes the condition, and by adding a maximum iteration counter.

Use while when the number of iterations depends on a result computed inside the loop, such as waiting for a value to cross a threshold. Use for when the sequence is known before the loop starts.

Iterative algorithms such as gradient descent, k-means, and expectation maximisation all run until convergence rather than for a fixed count, which is exactly the while pattern.

Yes. AI assistants can spot a missing counter update or a condition that can never turn FALSE. Always add a print statement or an iteration cap to confirm the diagnosis on your own data.

Summarize this post with: