8.2 The while Loop

The while loop combines the functionalities of loops and conditionals. It has the basic syntax while(expr){ ... } and executes the code ... as long as expr evaluates to TRUE.

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

It is relatively easy to create infinite loops if the condition is always TRUE. An example would be the following (be careful in trying it out!).

> x <- 1
> while(x > 0){
+   print(x)
+   x <- x + 1
+ }

Should you end up in an infinite loop, you will need to manually abort R. In RStudio, you can do this via the red STOP button in the console panel. If you run R on the command line, hit CTRL+C.

Note that most loops can be written both as a for or while loop and which one to use is a matter of choice. That said, if the length of a loop is known before hand (i.e. when looping over an object of known length), a for loop is usually preferred.

8.2.1 Exercises: While loops

See Section 18.0.20 for solutions.

  1. Replicate the call paste("I like number", 1:10) using a while loop.

  2. Write a loop that prints out the elements of c(5,6,8,2,3,7,8,1,2,3,4) until the first number that is smaller than 2.

  3. Use a loop to investigate the number of iterations I until the product i=1Ii reaches 5 million.