1. Repeat loops
Let's talk about loops. Whether you know it or not, you intuitively understand loops already.
2. Loops
In your daily life, you rely on them. Everyday you might wake up, shower, go to work or school, go to bed, and repeat this. This is an example of a loop. In science class,
3. Loops
if you ever studied the Water Cycle, you know that life exists because water evaporates, condenses, precipitates, and repeats that forever.
4. Repeat loop
In programming and in finance, loops are just as important, and there are a few different types of them in R. We will first talk about the simplest example, known as the repeat loop. Here is its most basic structure. This loop will increment i by 1, and then print it, resulting in 1, 2, 3, etc, over and over, for all eternity. This is called an infinite loop. Normally, we want to break out of the loop at some point,
5. Repeat loop
so an if statement is added to check for a condition to break on. The `break` command completely stops the loop when the condition is met. Here, i is incremented and printed, but during each iteration, the if statement checks to see if i equals 3. When it finally does, the loop stops.
6. Repeatedly check a stock price
A more sophisticated example might check a stock's daily movements, and tell you when to sell. In this example, you start with a stock price at 52.1. The price, incredibly simplified, is modeled by multiplying the current price by a random number between .99 and 1.01, a movement of between +/- 1%. Essentially this causes it to wiggle up and down. Each iteration, the stock_price moves up or down, is printed, and a condition is checked to see if the price went above 52.5. When it does, the loop breaks and a message is printed. As the creator of this loop, you have no idea when it is going to break. The random wiggling could hit 52.5 at any time! But by using a repeat loop with a condition, R will alert you right when it happens. In this case, it took seven movements before the stock price hit 52.5.
7. Let's practice!
Great. You'll get your hands dirty with repeat loops in the exercises. Let's get started.