Loops are used to repeat the process until the expression (condition) is TRUE. R uses three keywords for, while and repeat for looping purpose. Next and break, provide additional control over the loop.
The break statement exits the control from the innermost loop. The next statement immediately transfers control to return to the start of the loop and statement after next is skipped.
The value returned by a loop statement is always NULL and is returned invisibly.
The repeat statement executes the body of the loop until a break occurs. Be careful while using it because of the infinite nature of the loop. We must use the break statement to terminate the loop. The syntax of the repeat loop is :
The basic syntax for creating a repeat loop in R:
While is an another way to create a loop in R. It is very similar to the repeat loop. The syntax of the while loop is:
The basic syntax for creating a while loop in R:
In while loop, first, the expression is evaluated, and if it is TRUE, a block of statements execute. This process continues until the expression evaluated to FALSE.
R For loop
In R, for loop is a loop which is used to iterate the collection from the data structure like a vector. It uses in keyword to get individual elements from the vector. The syntax of the loop is:
This loop looks for each element in the data_collection and store keep into a variable data. So, we can use that variable to get the stored value.