for loop in R - break and next statement

For loop in R Programming Language is useful to iterate over the elements of a list, data frame, vector, matrix, or any other object. It means, the for loop can be used to execute a group of statements repeatedly depending upon the number of elements in the object. It is an entry controlled loop, in this loop the test condition is tested first, then the body of the loop is executed, the loop body would not be executed if the test condition is false.

for loop

It is a type of loop or sequence of statements executed repeatedly until exit condition is reached.

Syntax:

for(value in vector)
  statements .... .... 
}

Example:
for (i in seq(10)){
  cat(paste(i," "))
}
output:
1  2  3  4  5  6  7  8  9  10  


for (i in 1:10){
  cat(paste(i," "))
}
output:
1  2  3  4  5  6  7  8  9  10  
x <- letters[4:10]
for(i in x)
{
print(i)
}

output
[1] "d"
[1] "e"
[1] "f"
[1] "g"
[1] "h"
[1] "i"
[1] "j"

# R Program to demonstrate the use of
# for loop with vector
x <- c(-8, 9, 11, 45)
for (i in x)
{
cat(paste(i," "))
}

-8  9  11  45 

# Iterate a sequence and square each element
for (x in seq(from=2,to=8,by=2)) {
  print(x^2)
}
output:
[1] 4
[1] 16
[1] 36
[1] 64
Nested loop to handle matrix
# Defining matrix
m <- matrix(2:9, 2)
print(m)
for (r in seq(nrow(m))) {
for (c in seq(ncol(m))) {
print(m[r, c])
}
}
output
[,1] [,2] [,3] [,4]
[1,]    2    4    6    8
[2,]    3    5    7    9
[1] 2
[1] 4
[1] 6
[1] 8
[1] 3
[1] 5
[1] 7
[1] 9


Jump Statements in R

We use a jump statement in loops to terminate the loop at a particular iteration or to skip a particular iteration in the loop. The two most commonly used jump statements in loops are:
Break Statement:

A break statement is a jump statement which is used to terminate the loop at a particular iteration. The program then continues with the next statement outside the loop(if any).

Example:
# R Program to demonstrate the use of
# break in for loop
for (i in c(3, 6, 23, 19, 0, 21))
{
if (i == 0)
{
break
}
print(i)
}
print("Outside Loop")

output
[1] 3
[1] 6
[1] 23
[1] 19
[1] "Outside Loop"

Here the loop exits as soon as zero is encountered.

Next Statement

It discontinues a particular iteration and jumps to the next iteration. So when next is encountered, that iteration is discarded and the condition is checked again. If true, the next iteration is executed. Hence, the next statement is used to skip a particular iteration in the loop.

Example:
# R Program to demonstrate the use of
# next in for loop
for (i in c(3, 6, 23, 19, 0, 21))
{
if (i == 0)
{
next
}
print(i)
}
print('Outside Loop')

output
[1] 3
[1] 6
[1] 23
[1] 19
[1] 21
[1] "Outside Loop"

Comments

Popular posts from this blog

Programming in R - Dr Binu V P

Introduction

R Data Types