Trusted answers to developer questions

How to use for loops in R

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

Overview

A for loop in R is used to iterate over a sequence for a specific number of times. The number of iterations is determined by a conditional statement (the expression) within the for loop.

To declare a for loop in R, use the syntax below:

for(expression){
  statement(s)
}

The expression represents the given condition, while the statement represents what the code should execute if the expression is TRUE.

for loops are especially useful if you need to repeat the same code until a particular condition is met.

Example 1

for (x in 1:5) {
print(x)
}

Explanation

In the code above, we state a condition that for x having values starting from 1 to 5 (these are the iterations), R should print all of the values of x.

This for loop is not like the for keyword in other programming languages, but rather more of an iterator method that can be found in other object-oriented programming languages.

Example 2

We can also print all the items of a list with a for loop.

countries <- list("USA", "FRANCE", "UK", "CANADA")
for (x in countries) {
print(x)
}

Explanation

In the code above, we create a list variable named countries and use the for loop to iterate over each item of the list. We then ask R to print all the items in the list.

Note: The for loop differs from the while loop because the for loop does not require an index variable, unlike the while loop.

RELATED TAGS

r

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
Did you find this helpful?