Loops are one of the basic concepts of pro­gram­ming. They ensure that certain passages of code are executed re­peatedly under a certain condition. With while loops in R, a section is repeated until the pre­vi­ously specified condition becomes false.

What are while loops in R used for?

While loops are used to re­peatedly 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 fre­quently used in R pro­gram­ming to learn about elements of an R list and perform specific actions on them in­di­vidu­ally. 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 con­di­tion­al execution of code. Loops like the while loop are the basis of many well-known sorting al­gorithms 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 pro­gram­ming languages. In the loop header, which is in­tro­duced with the while keyword, the condition is specified in par­en­theses. 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 il­lus­trate 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

Bubble­sort in R example

Bubble­sort 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 bubble­sort 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 Bubble­sort, until the sorting is complete.

Break in while loop in R

To pre­ma­turely 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 ter­min­ated pre­ma­turely 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, re­gard­less 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 it­er­a­tions is known in advance. The number of it­er­a­tions is ex­pli­citly 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, re­gard­less of a condition. If you’re not just starting out in pro­gram­ming, you’re probably familiar with do-while loops from other pro­gram­ming languages like Java. There is no explicit do-while loop in R where a block of code is executed at least once. But the func­tion­al­ity can be easily im­ple­men­ted 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. be736e550b1141b116c6745223aecfd7

d1d76d85f27f41c7f98c49bcb7641848

37b614e8ff1142c9025056cc2b26f936

f73edeee674565a3ba93d621869650b4

Go to Main Menu