R For Loop
The for
loop in R is used to iterate over a sequence, such as a vector, list, or range of numbers. It is ideal for scenarios where the number of iterations is predetermined.
Key Topics
For Loop Syntax
The syntax for a for
loop in R is as follows:
for (variable in sequence) {
# Code to execute
}
In this syntax, variable
takes each value in the sequence, and the code block is executed for each value.
For Loop Example
# Example of a for loop
for (i in 1:5) {
print(paste("Value of i is:", i))
}
Output:
[1] "Value of i is: 1"
[1] "Value of i is: 2"
[1] "Value of i is: 3"
[1] "Value of i is: 4"
[1] "Value of i is: 5"
[1] "Value of i is: 2"
[1] "Value of i is: 3"
[1] "Value of i is: 4"
[1] "Value of i is: 5"
Code Explanation: The for
loop iterates over the sequence 1:5
. During each iteration, the value of i
is printed.
Key Takeaways
- The
for
loop is used when the number of iterations is known. - It can iterate over any iterable object, such as vectors, lists, or ranges.
- Ensures that the code block executes for each element in the sequence.