The for loop executes the same code again and again for a specific number of times.
Problem:
Write a for loop in R
Solution:
The simple syntax of for loop is as below:
for(variable in sequence)
{
expressions
}
Example:
Analysis:
- Created a Vector with the seven days of a week
- R realizes the sequence is a Vector containing 7 elements.
- The variable is “day” and the for loop will execute the expression for each day in the Vector “days”
- For the 1st iteration, the first element of the Vector is assigned to the variable day. i.e. “Sunday”.
- The expression inside the for loop gets executed and thus R is printing the day
- For the 2nd iteration, the 2nd element of the vector is assigned to the variable day i.e. “Monday” and then R is printing the 2nd day.
- Similarly, the for loop will iterate 7 times, executing the expression inside the loop for each day of the vector days.
For Loop Over List:
Looping over a List is similar to the looping over a vector.
The output is also exactly the same as the Vector example.
The output is also exactly the same as the Vector example.
Break a Loop:
The break statement in a loop stops the execution of the code and exits the active loop. Thus the remaining part of the code in the loop is skipped and the loop is not iterated over anymore.
Thus, for the above piece of code, the output is as below:
The For Loop printed the days till “Wednesday”. Once the day is “Thursday”, R exits the loop and thus the rest of the elements of the vector are not printed.
Next in Loop:
The next statement skips the rest of the code in the loop but continues the iteration.
For the above example, if we replace the break statement with the next, the output looks different.
In this scenario, R prints the days till “Wednesday, skips “Thursday” and then continue the iteration printing the rest of the elements of the Vector.