R is a functional, object-oriented language that, like almost all other programming languages, supports the for loop control structure. A for loop in R allows you to perform iterations by enumeration or to set up counting loops.
Application possibilities¶
Whether you are just starting to learn programming or are used to developing your own programs, chances are you have already crossed paths with a for loop.
As is also the case with other languages, a for loop is always used in R programming when the number of loop iterations is known beforehand and what you want run certain blocks of code repeatedly. The for loop is therefore a safe bet if you want, for example, to implement a counter capable of going up to the number 5 in your program.
Many programming languages, like Java, also support the concept of a foreach loop, which allows direct iteration over an array or list, as well as access to each element of the data structure. This loop is particularly handy if you are looking to perform an operation on all the elements of the same data structure. This variant of the for loop is also supported in the R programming language; the foreach loop is also introduced by the “for” keyword.
In practice, every for loop in R can also be replaced by a while loop. In addition to better readability, for loops mainly offer the most compact code.
For loop in R: syntax¶
To use a for loop in R, it is necessary to take into account the syntactic peculiarities of the construction of the loop.
In essence, a for loop consists of two essential elements, respectively called the header And the body of the loop. Since for loops in R are header-controlled loops, the header executes first. The code specified in the loop body only executes if the condition you set is met.
The loop header is introduced by the “for” keyword. Next, the name of your count variable (or counter) is specified in parentheses, followed by the keyword « in ». Next, you need to specify the exact iteration you want. It can be, for example, a series of numbers, but also a list or even a vector. Then the body of the loop is itself specified usingbraces.
Different for loops in R:¶
Counting loops¶
Similar to for loops in Python, for loops in R work primarily using a number range. Thus, you will find below an example of a for loop in R allowing to display on the screen all the numbers from 1 to 10:
for (x in 1:10) {
print(x)
}
R
In the sample code above, a variable x is embedded in the header of the for loop in R. The « in » keyword is used to specify that this variable should move through the range of values between 1 and 10. The R language automatically supports l ‘increment, whole number by whole number. Warning: unlike Python’s “range” function, the number mentioned in the second position is included in the increment.
With your counting loop, you can also opt for decrementing from a number. To do this, simply swap the two limits in the loop header and specify the larger number first. Again, the R language automatically takes care of this decrement for you:
for (x in 10:1) {
print(x)
}
R
Your program then displays on the screen all the integers starting with 10 and stopping at 1.
foreach loops¶
You can implement the logic corresponding to foreach loops in the R programming language, but if no keyword specific to these loops is integrated into it. In R, these loops are also introduced by the “for” keyword:
cars <- list("limousine", "cabrio", "suv")
for (x in cars) {
print (x)
}
R
In the example above, different types of cars have been saved in a list called » cars « . The for loop in R that follows it sets up an iteration over each of its elements, and displays it on the screen. The name of the element to be iterated over (here it is the list » cars ”) is also filled in just after the keyword “in”.
Ending a for loop in R: the “break” keyword¶
Say you want to find a specific item in a list; it may be a good idea to know how to end the for loop once the element in question is found. This trick often avoids unnecessary iterations of the loop and spares the computing power of your program. To help you, the R language offers the keyword “break” :
cars <- list("limousine", "cabrio", "suv", "supersport", "oldtimer")
for (x in cars) {
print (x)
if (x == "suv") {
break
}
}
R
In the sample code above, we’ve extended the list called » cars « . However, we would like the different car types to stop displaying once the « SUV » type is found. All you have to do is use the “break” keyword already mentioned as part of the if…else condition in R.
Skipping iterations of for loops in R: the “next” keyword¶
In some application cases, it may be more useful toskip some loop iterations than directly terminating the execution of the entire for loop. To achieve this, the R programming language offers another suitable keyword, “next”:
cars <- list("limousine", "cabrio", "suv", "supersport", "oldtimer")
for (x in cars) {
if (x == "suv") {
next
}
print(x)
}
R
The sample code above has been modified so that all car types in the list are displayed, except SUVs. To do this, we also used an if condition responsible for checking whether or not the current list item is an SUV. If so, the other statements in the loop body are skipped and execution of the for loop in R continues normally.