1. For loops
Lastly, you'll learn about another common type of loop, the for loop. When you can figure out in advance
2. For loop
how many iterations your loop should perform, it is common to use a for loop. The idea behind this is slightly different than with while loops and repeat loops. Instead of checking a condition, you perform a set number of iterations over a sequence of elements. In more concrete terms, this means that if you had a sequence of numbers from 1 to 5 to loop over, the loop would run 5 times. How do you actually implement this? Let's find out. The variable one_to_five is a sequence from 1 to 5. To set up a for loop, we use the keyword for, and inside the parenthesis we define what we want to loop over. Here, we want to loop over each number in the variable one_to_five. The word number could have been anything like i or iterator, but here it makes sense to use number because that is what each element of one_to_five is. The keyword in is used in all for loops to define what you are looping over. Like the other loops, the repeated code occurs inside braces. Notice that you have access to the current iteration's variable, number, which here contains 1 in the first iteration, 2 in the second, and so on. Once the 5th iteration is complete, the loops stops.
3. Loop over a list
For loops can loop over more complex objects than just vectors of numbers. Consider this stock _list_ of 4 elements. What if you wanted to perform a calculation on each element in the list, like determining what the class of that element is. Just looking at stock_list, you can see that some elements are characters, some are numerics, and some are logical. You can set up the for loop in the same way as before, this time telling R to loop over stock_list. The variable i will contain the current element of the list. During the first iteration, i contains the character "Apple", during the second, the character "AAPL", during the third, the numeric 126-point-5, and so on. The print function is necessary when you want to print to the console from inside a loop, without it, nothing gets printed outside of the loop even though the calculations are performed.
4. Let's practice!
Great! In the exercises you will learn to loop over rows of a data frame, and perform a nested loop over elements in a correlation matrix. Have fun!