R For Loop

R For Loop

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!


Iterating Over a Sequence

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!

Sequence Example:

# This prints numbers from 1 to 5
for (x in 1:5) {
  print(x)
}

Iterating Over a List

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!

List Iteration Example:

fruits <- list("apple", "banana", "cherry")
# Loops through each element in the list
for (x in fruits) {
  print(x)
}

The break and next Statements

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.


Exercise 1 of 2

?

Which operator is used to quickly generate a sequence of numbers in R?

Exercise 2 of 2

?

Why are 'for' loops generally considered safer than 'while' loops?