Updated March 21, 2023
Introduction to For Loop in R
A concept in R that is provided to handle with ease, the selection of each of the elements of a very large size vector or a matrix, can also be used to print numbers for a particular range or print certain statements multiple times, but whose actual function is to facilitate effective handling of complex tasks in the large-scale analysis is called as For loop in R. It is syntactically slightly different from the same concept in other programming languages, and belongs to the family of looping functionalities in R.
For Loop Syntax
The for loop syntax in R is similar to that of python or any other language.
For example, below is the syntax of for loop in R.
Syntax:
for (val in sequence) {
Statement
}
In the above syntax, the vector is represented by sequence, and val is the value of the vector during the For Loop.
Now let’s see the process undertaken by for loop condition with the help of a flow chart. First, the loop repeats itself for every item in the sequence until the required condition is reached. Then, the condition is checked, and when the last item is reached compiler exists the loop.
The structure consists of initialization shown as “init,” the rhombus, a decision box, and a rectangular box that is the body of the for a loop. While executing a set of commands under for loop condition, the compiler doesn’t start the loop until the condition is specified. If there is no condition available, the next instruction after the loop will be executed. For each item in the sequence, the condition is matched. Until the condition isn’t matched, the loop goes over and over again. Once the last item or the condition is satisfied, the compiler exists in the loop.
How For Loop Works in R?
Before learning how For Loop works in R, let’s see what a loop or looping is. Loop or iteration, which is basically an instruction to repeat, has its origin dated long back. In simple terms, it’s automating the process by grouping certain required functions in a batch of parts. Most of the modern programming language has an inbuilt looping function that allows building a function for automation. The looping functions can be divided into two parts, loops that are controlled and can be executed the desired number of times falls under for loop family. On the other hand, the loops that are based on a set of conditions fall under the while loop family.
In this article, we will investigate the different methods available in R for the purpose of looping. We will further look at different looping examples using functions available in the R library. While working in R language, For loops are only looping conditions you will require, rarely there might be a need for other looping conditions such as while. Let’s see how For loop is used to iterate over numerical values.
Code:
# for printing number from 9 to 99 usinf for loop
> for(i in 9:99){
+ print(i)
+ }
[1] 9
[1] 10
[1] 11
[1] 12
[1] 13
[1] 14
[1] 15
[1] 16
[1] 17
[1] 18
[1] 19
[1] 20
[1] 21
In the above example, the variable “i” is taken by the loop and iterated until the condition is satisfied. Printing the variable “i” inside the loop gives us with values ranging from 9 to 99. Now, let’s see another example using characters.
Code:
# for printing and looping items in example vector
> example <- c("cat", "dog", "bill", "base")
> for(i in 1:4)
+ {
+
+ print(example[i])
+ }
[1] "cat"
[1] "dog"
[1] "bill"
[1] "base"
# In case we don’t want the entire loop to be executed
# loop can be stopped with the help of break condition
# In the below example the fourth element will not be printed.
> example <- c("cat", "dog", "bill", "base")
> for(i in 1:3)
+ {
+
+ print(example[i])
+ }
[1] "cat"
[1] "dog"
[1] "bill"
In the above example, we are printing out desired elements from the example. In the first example, four elements are called out in the sequence; hence all the elements have been printed when the print statement has been executed. In the second example, the sequence has been called until the third element; hence the first three elements are printed.
On the other hand, there is a repeat loop condition, which has similar functionality to that of the loop. However, repeat condition is used to iterate over code continuously without a condition check.
The user needs to define a condition inside the loop, and a “break” statement must be used to exit the loop. Failing to use the “break” statement will result in an infinite loop.
Code:
# illustrating repeat statement to print numbers from 5 to 15
> n <- 5
> repeat
+ {
+ print(n)
+ n = n+1
+ if (n == 16){
+ break
+ }
+ }
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
[1] 11
[1] 12
[1] 13
[1] 14
[1] 15
In the above example, we have specified the condition n == 16 so that the compiler stops the loop when the n == 6 is reached.
For Loop Examples
To introduce For loops in R, let us take an example of extracting elements or items from the vector.
Code:
> states <- c('Oregon', 'Florida', 'Texas', 'Lowa', 'Nebraska', 'utah')
>
>
> for (str in states) {
+ print(paste("States in USA: ",str))
+ }
[1] "States in USA: Oregon"
[1] "States in USA: Florida"
[1] "States in USA: Texas"
[1] "States in USA: Lowa"
[1] "States in USA: Nebraska"
[1] "States in USA: utah"
# to illustrate the print operation outside the loop
> print("----prints outside the loop---")
[1] "----prints outside the loop---"
Step 1
Vector named states has been defined, which consists of different states
> states <- c('Oregon', 'Florida', 'Texas', 'Lowa', 'Nebraska', 'Utah')
Step 2
In the next step, for loop is used to iterate over states vector and display the individual name of the states.
> for (str in states) {
+ print(paste("States in USA: ",str))
+ }
As the print statement is included inside the loop, we get the desired results, and all the names of the states are printed. In the next step, another print statement is used outside the loop, which practically executes once the for-loop ends.
Now let’s see the logic behind every iteration during the execution of the code.
- During the first iteration, State = Oregon, there are elements remaining in the vector. Hence, the print statement is executed by the compiler inside the loop.
- During the second iteration, State = Florida, there are four more elements remaining in the vector. Hence, the print statement is executed by the compiler inside the loop.
- During the third iteration, State = Texas, there are three more elements remaining in the vector. Hence, the print statement is executed by the compiler inside the loop.
- During the fourth iteration, State = Lowa, there are two more elements remaining in the vector. Hence, the print statement is executed by the compiler inside the loop.
- During the fifth iteration, State = Nebraska, there is another one element remaining in the vector. Hence, the print statement is executed by the compiler inside the loop.
- During the sixth iteration, State = Utah, there might be elements remaining in the vector. Hence, the print statement is executed by the compiler inside the loop.
- During the seventh iteration, as there are no more elements to assign for the state variable, the compiler will exit the loop.
In the next example, let’s see the loop functionality in the case of integers.
Code:
> num <- c(1:5)
>
> for (i in num) {
+ print(i)
+ }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Step 1: Vector named num has been defined, which consists of integers from 1 to 5.
> num <- c(1:5)
Step 2: In the next step, the loop is used to iterate over a num vector and display the individual integers.
> for (i in num) {
+ print(i)
+ }
As the print statement is included inside the loop, we get the desired results and all the integers from the vector num are printed.
Now let’s see the logic behind every iteration during the execution of the code.
- During the first iteration, “1”, there are elements remaining in the vector. Hence, the print statement is executed by the compiler inside the loop.
- During the second iteration, “2”, there are three more elements remaining in the vector. Hence, the print statement is executed by the compiler inside the loop.
- During the third iteration, “3”, there are two more elements remaining in the vector. Hence, the print statement is executed by the compiler inside the loop.
- During the fourth iteration, “4”, there is still one more element remaining in the vector. Hence, the print statement is executed by the compiler inside the loop.
- During the fifth iteration,”5”, there might be elements remaining in the vector. Hence, the print statement is executed by the compiler inside the loop.
- During the sixth iteration, as there are no more elements to assign for the num variable, the compiler will exit the loop.
Conclusion
In this article, we have seen how for loop condition can be executed using R, R studio has been used to perform the above operations, and the results have been displayed. We have further seen an example of extracting elements or items from the vector, and evaluation for each step has been investigated in the article.
Recommended Articles
This is a guide to For Loop in R. Here we discuss how for loop works in R with the appropriate examples and syntax respectively. You may also have a look at the following articles to learn more –