Next Statement in R Programming Langiage

Rumman Ansari   Software Engineer   2023-03-24   5744 Share
☰ Table of Contents

Table of Content:


A next statement is useful when we want to skip the current iteration of a loop without terminating it. On encountering next, the R parser skips further evaluation and starts next iteration of the loop.


The syntax of next statement is:

if (test_condition) {
next
}

Note: the next statement can also be used inside the  else branch of if...else statement.


Flowchart of next statement

Flowchart of next in R programming


Example 2: Next statement

x <- 1:5
for (val in x) {
if (val == 3){
next
}
print(val)
}

Output

[1] 1
[1] 2
[1] 4
[1] 5

In the above example, we use the next statement inside a condition to check if the value is equal to 3.

If the value is equal to 3, the current evaluation stops (value is not printed) but the loop continues with the next iteration.

The output reflects this situation.

Operation on a matrix using apply

Code


theMatrix <- matrix(1:9, nrow = 3)
theMatrix

# sum of columns
apply(theMatrix, MARGIN = 2, sum)

# sum of rows
apply(theMatrix, MARGIN = 1, sum)

# same as previous one
colSums(theMatrix)

# same as previous one
rowSums(theMatrix)

theMatrix[2,1] <- NA 
theMatrix

apply(theMatrix, MARGIN = 1, sum)
# remove NA
apply(theMatrix, MARGIN = 1, sum, na.rm = TRUE)


# do the same thing
rowSums(theMatrix, na.rm = TRUE)


Output


> theMatrix <- matrix(1:9, nrow = 3)
> theMatrix
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
> 
> # sum of columns
> apply(theMatrix, MARGIN = 2, sum)
[1]  6 15 24
> 
> # sum of rows
> apply(theMatrix, MARGIN = 1, sum)
[1] 12 15 18
> 
> # same as previous one
> colSums(theMatrix)
[1]  6 15 24
> 
> # same as previous one
> rowSums(theMatrix)
[1] 12 15 18
> 
> theMatrix[2,1] <- NA 
> theMatrix
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]   NA    5    8
[3,]    3    6    9
> 
> apply(theMatrix, MARGIN = 1, sum)
[1] 12 NA 18
> # remove NA
> apply(theMatrix, MARGIN = 1, sum, na.rm = TRUE)
[1] 12 13 18
> 
> 
> # do the same thing
> rowSums(theMatrix, na.rm = TRUE)
[1] 12 13 18