How to use the for loop in R

R is one of the many programming languages that support the for-loop control structure. R is a functional and object-oriented language. The for loop in R allows users to iterate through enumeration or implement counting loops.

What are its applications?

Whether you’re just beginning to learn programming or have been developing your own programs for a while, you’ve probably encountered for loops.

A for loop is used in R programming when the user knows the number of loops in advance and wants certain blocks of code to be executed repeatedly. The for loop is the go-to, for example, if you want to use a counter in your program that counts up to the number five.

Many programming languages, such as Java, support the foreach loop. This lets you iterate directly through an array or list and gives access to each element of the data structure. This is useful if you want to perform an operation on all elements of a data structure. This for loop variant is also supported in R. The foreach loop in R is also introduced with the keyword ‘for’.

However, every for loop in R can also be replaced with a while loop. The main advantage of using for loops is their compact and readable code.

Tip

Webspace from IONOS allows you to securely put all your projects online. Regular backups ensure your programs are protected against data loss.

What is the R for loop syntax?

The for loop in R has some syntactic features which users should keep in mind.

A for loop consists of two essential elements, the loop head and the loop body. For loops in R are head-controlled loops, meaning the loop head is carried out first. If the specified statement is met, the code formulated in the loop body will be executed.

The loop header is introduced with the keyword ‘for’. The name of the count variable is placed in round brackets followed by the keyword ‘in’. You must then specify exactly what you want to iterate through. For example, this can be a number range, a list or a vector. The following loop body is shown in curly brackets.

What are the different for loops in R?

Counting loops

Similarly to for loops in Python, for loops in R focus on a range of numbers. If you want to output all numbers between 1 and 10, this is how the R for loop would look:

for (x in 1:10) {
	print(x)
}
R

This code example introduces the x variable in the R for loop’s loop header. The keyword ‘in’ is specified for this variable and ensures that it moves within a value range between 1 and 10. Incrementation is done by R automatically. You may have noticed that, unlike the Python range function, the highest value is included in the output.

You can also count down from a number in a counting loop. Simply swap the two limits in the loop header and put the larger number first. R will automatically decrement for you:

for (x in 10:1) {
	print(x)
}
R

Your program will output all integers starting at 10 and ending at 1.

Foreach loops

Although R does not have its own keyword for foreach loops built in, you can use the foreach loops logic in the programming language. These loops are also introduced with the keyword ‘or’ in R:

cars <- list("limousine", "convertible", "suv")
for (x in cars) {
	print (x)
}
R

A list called cars is displayed in the example above and it contains different types of cars. The subsequent R for loop iterates over each element from this list and displays it on the screen. The name of the element you want to iterate through, cars in this case, is also specified after the keyword ‘in’.

How to break off an R for loop with the keyword ‘break’

If you want to search for a specific element in a list, it is useful to terminate your for loop when you have found the corresponding element. This prevents unnecessary loop iterations and reduces the amount of computing power required by the program. R offers the keyword ‘break’ for this purpose:

cars <- list("limousine", "cabrio", "suv", "supersport", "oldtimer")
for (x in cars) {
print (x)
	if (x == "suv") {
		break
}
}
R

The code example above shows an expanded list named cars. However, we want to stop the output of car types as soon as we have found ‘SUV’. Use the keyword ‘break’ in the R if else statement.

How to skip loop iterations of R for loops with the keyword ‘next’

In some applications, it may be helpful to skip certain loop iterations instead of stopping the entire for loop. The R programming language offers the keyword ‘next’ for this situation:

cars <- list("limousine", "cabrio", "suv", "supersport", "oldtimer")
for (x in cars) {
	if (x == "suv") {
		next
}
print(x)
}
R

The code example above has been modified. It will output all car types from the list except ‘SUV’. An if statement checks if SUV is in the current list. If it is, the remaining statements in the loop body are skipped and the R for loop continues.

Was this article helpful?
Page top