How do while loops in R work?

Loops are one of the basic concepts of programming. They ensure that certain passages of code are executed repeatedly under a certain condition. With while loops in R, a section is repeated until the previously specified condition becomes false.

What are while loops in R used for?

While loops are used to repeatedly execute a block of code depending on a condition. As long as this condition is true, the code in the while loop is executed.

Loops are frequently used in R programming to learn about elements of an R list and perform specific actions on them individually. For example, you can output any string on the screen from a list of R strings. In addition, while loops in R are used for the conditional execution of code. Loops like the while loop are the basis of many well-known sorting algorithms that organise a database according to certain criteria.

Structure and syntax of while loops in R

The syntax of while loops in R is similar to that of while loops in most other programming languages. In the loop header, which is introduced with the while keyword, the condition is specified in parentheses. The latter must be true for the loop hull to be executed. This hull is nothing more than its own block of code after the loop head, enclosed in curly brackets.

To illustrate this, we’ve created an example. This R loop example shows a while loop that outputs values from 1 to 10:

x <- 1
while (x <= 10) {
    print(x)
    x <- x + 1
}
R

Bubblesort in R example

Bubblesort is a classic sorting algorithm used to sort elements of an R vector or an array in R in ascending order. In this sorting algorithm, a while loop is used to execute the sorting code until all elements of the vector are sorted:

bubblesort <- function(x) {
    swapped <- TRUE
    n <- length(x) - 1
    while (swapped) {
        swapped <- FALSE
        for (i in 1:n) {
            if (x[i] > x[i+1]) {
                tmp <- x[i]
                x[i] <- x[i+1]
                x[i+1] <- tmp
                swapped <-TRUE
                }
        }
    }
    return(x)
}
R

In the above code, an R function called bubblesort is created. This ensures that a numerical vector is sorted in ascending order. The while loop is used to carry out the exchange process, which is essential for Bubblesort, until the sorting is complete.

Break in while loop in R

To prematurely exit a while loop under a certain condition, you can use the ‘break’ keyword. This ensures that the loop is left and not re-entered. Here’s an example of the ‘break’ statement to explain:

x <- 10
while (x >= 0) {
    print(x)
    if (x == 5) {
        break
        }
        x <- x - 1
}
R

The above loop outputs numbers from 10 to 5 on the screen. When the variable ‘x’ reaches the value 5, the R ‘if’ condition is executed and the loop is terminated prematurely by calling ‘break’.

Other loops in R

The while loop in R isn’t the only kind of loop in R. There’s also the for loop, which is often thought of as a kind of counting loop, and the repeat loop, which is used to execute code multiple times, regardless of a condition. Repeat loops must be exited with the ‘break’ keyword, otherwise they are infinite loops.

For loop in R

For loops are used when the number of iterations is known in advance. The number of iterations is explicitly specified in the loop header. A for loop that outputs numbers from 1 to 5 looks like this:

for (z in 1:5) {
print(i)
}
R

Repeat loop in R

Repeat loops in R are used to execute code multiple times, regardless of a condition. If you’re not just starting out in programming, you’re probably familiar with do-while loops from other programming languages like Java. There is no explicit do-while loop in R where a block of code is executed at least once. But the functionality can be easily implemented with repeat loops:

x <- 1
repeat {
    print(x)
    if (x >= 10) {
        break
        }
x <- x + 1
}
R

The above code example outputs numbers from 1 to 10. The code is executed at least once (in a classic do-while loop in the ‘do codeblock’) before the ‘if’ statement, which ends the loop if the specified condition is true.

Was this article helpful?
Page top