Get startedGet started for free

While loops

1. While loops

Let's talk about another type of loop in R, the while loop. These are actually very easy to understand if you understand if statements. Essentially,

2. While loop

a while loop is a repeated if statement. Let's see what I mean by that. Look at the structure of a simple while loop. If the condition in parenthesis is true, the code in the braces gets executed, just like an if statement. The difference is that once the code has finished executing, the condition is checked again, and the process is repeated as long as the condition is true. For that reason, it is important that you ensure your condition will always evaluate to false at some point, otherwise you have an infinite loop. That is done here by incrementing i inside the loop. Before the 4th iteration, i will be not be strictly less than 3, and at that point, it will stop the loop.

3. Check while true

We can recreate our wiggling stock price example using a while loop. Notice that compared to the repeat loop, the if statement has been removed, and the condition has been moved to the top. Also note that the ending print statement has been moved outside the loop. The actual execution is almost identical, the stock price is checked to be less than or equal to 52-point-5, it is then allowed to move, the new price is printed, and the process is repeated, until we go above our condition. This time, it took 5 iterations before our stock price went above 52-point-5.

4. Let's practice!

While loops are great when you don't know the exact number of iterations that you need to perform, and instead want it to break when a condition is met. Let's practice!

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.