0
0
R Programmingprogramming~10 mins

For loop in R Programming - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - For loop
Initialize loop variable i = 1
Check condition: i <= 5?
NoEXIT loop
Yes
Execute loop body
Update i: i = i + 1
Back to condition check
The loop starts by setting a variable, checks if it meets a condition, runs the code inside if yes, then updates the variable and repeats until the condition is false.
Execution Sample
R Programming
for (i in 1:5) {
  print(i)
}
This code prints numbers from 1 to 5, one number per line.
Execution Table
IterationiCondition (i in 1:5)ActionOutput
11TRUEprint(i)1
22TRUEprint(i)2
33TRUEprint(i)3
44TRUEprint(i)4
55TRUEprint(i)5
💡 After iteration 5, the sequence 1:5 is exhausted (no more values), so the loop stops. i remains 5.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
iNA123455
Key Moments - 2 Insights
Why does the loop stop after printing 5?
Because the loop variable i goes from 1 to 5. After i=5, there are no more values in the sequence 1:5, so the loop ends (see execution_table).
Is the loop variable i available after the loop ends?
Yes, in R the variable i still exists after the loop and has the last value it took, which is 5 here (see variable_tracker final value).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of i during the 3rd iteration?
A3
B2
C4
D5
💡 Hint
Check the 'i' column in the execution_table row for iteration 3.
How many times does the loop body run?
A6
B1
C5
D7
💡 Hint
Count the number of rows where Condition is TRUE or Action is 'print(i)' in the execution_table.
If the loop was changed to for(i in 1:3), how many times would the loop body run?
A5 times
B3 times
C6 times
D1 time
💡 Hint
The loop runs once for each number in the sequence 1:3, check variable_tracker for similar pattern.
Concept Snapshot
for (variable in sequence) {
  # code to repeat
}

- Runs code for each value in sequence
- variable takes each value in order
- Stops after last value
- Loop variable keeps last value after loop
Full Transcript
A for loop in R repeats a block of code for each value in a sequence. It starts by setting a variable to the first value, checks if it is in the sequence, runs the code, then moves to the next value. This continues until all values are used. In the example, the loop prints numbers 1 to 5. The variable i changes from 1 to 5 during the loop and remains 5 after the loop ends because the sequence is exhausted. This shows how the loop controls repetition clearly and simply.