Getting Started with R Language - Loop

循环

R Programming Language provides the following kinds of loops to handle looping requirements. Click on the link below to check its details.

No. 循环type and description 语法
1 repeat Loop

executes a series of statements multiple times and simplifies the code for managing loop variables.

repeat {

commands if(condition)

{ break }

}

2 while Loop

Executes the statement when the given condition is true. It executes the statement first and then determines if the condition is met.

while (expression) { statement }
3 for loop

is similar to the while statement, the difference is that it first determines whether the condition is met, and then executes the statement

for (expression) { statement }

example:repeat

v <- c("Hello","loop")
cnt <- 2

repeat {
   print(v)
   cnt <- cnt+1
   
   if(cnt > 5) {
      break
   }
}

When the above code is compiled and executed , it produces the following result -

[1] "Hello" "loop" 
[1] "Hello" "loop" 
[1] "Hello" "loop" 
[1] "Hello" "loop" 

example: while

v <- c("Hello","while loop")
cnt <- 2

while (cnt < 7) {
   print(v)
   cnt = cnt + 1
}

When the above code is compiled and executed, it produces the following result -

[1] "Hello"  "while loop"
[1] "Hello"  "while loop"
[1] "Hello"  "while loop"
[1] "Hello"  "while loop"
[1] "Hello"  "while loop"

example :for

v <- LETTERS[1:4]
for ( i in v) {
   print(i)
}

when the above code is compiled and When executed, it produces the following result -

[1] "A"
[1] "B"
[1] "C"
[1] "D"

loop control statement

The loop control statement changes execution from its normal sequence. When the execution leaves the scope, all automatic objects created in that scope are destroyed. The R language supports the following control statements. Click on the link below to check its details.

Sr.No. Control statement and description
1 break statement

Terminates the loop statement and transfers the execution to the statement executed immediately after the loop. The

2 next statement

next statement simulates the behavior of the R language switch statement. Use next when we want to skip the current iteration of the loop without terminating it.

example:break

v <- c("Hello","loop")
cnt <- 2

repeat {
   print(v)
   cnt <- cnt + 1
	
   if(cnt > 5) {
      break
   }
}

When the above code is compiled and executed, it produces the following result -

[1] "Hello" "loop" 
[1] "Hello" "loop" 
[1] "Hello" "loop" 
[1] "Hello" "loop" 

example: next

v <- LETTERS[1:6]
for ( i in v) {
   
   if (i == "D") {
      next
   }
   print(i)
}

When the above code is compiled and executed, it produces the following Result -

[1] "A"
[1] "B"
[1] "C"
[1] "E"
[1] "F"