A for loop is heavily used for iterating over an exact sequence or structure.
This is significantly safer than a while loop, as it naturally prevents infinite loops!
In R, you can easily generate a sequence of numbers using the colon : operator.
The syntax for (x in 1:10) commands the loop to execute exactly ten times.
During each cycle, the variable x will automatically update to the next number in the sequence!
# This prints numbers from 1 to 5
for (x in 1:5) {
print(x)
}
For loops are exceptionally powerful when you need to process large data structures.
You can iterate securely over every single item inside a list or array!
fruits <- list("apple", "banana", "cherry")
# Loops through each element in the list
for (x in fruits) {
print(x)
}
Exactly like the while loop, you can utilize break and next inside a for loop.
This provides ultimate control over exactly how and when your dataset is parsed.
Which operator is used to quickly generate a sequence of numbers in R?
Why are 'for' loops generally considered safer than 'while' loops?