Control Structures in R – Execute 8 Types of Loops With Their Examples

Control Structures in R is used to control the execution flow of expressions series. These control structures also called as Loops in R. Today, we will study these eight types of Control Structures in R with their examples and execution flow.

  • if
  • if-else
  • for
  • nested loops
  • while
  • repeat and break
  • next
  • return

Control Structures in R Programming

R has the standard control structures we would expect. expr can be multiple statements by enclosing them in braces { }. It is more efficient to use built-in functions in R rather than control structures whenever possible. These allow us to control the flow of execution of a script typically inside of a function.

Control structures define the flow of the program. The decision is been based on the evaluation of a variable.

List of R Control Structures with Examples

Now we will discuss these Control Structures in R one by one in detail:

Control Structures in R Programming

1. If Loop in R

If this condition is true, then carry out a certain task. R makes it even easier: You can drop the word then and specify your choice in an if statement.

Syntax

if (test_expression) {
statement
}

Example

values <- 1:10                                        
if (sample(values,1) <= 10)                               
print(paste(values, "is less than or equal to 10"))

 

If Loop in R

R Data Types plays an important role in Control Structures

2. If-else Loop in R

An if…else statement contains the same elements as an if statement (see the preceding section), and then some extra:

  • The keyword else, placed after the first code block
  • A second block of code, contained within braces, that has to be carried out if and only if the result of the condition in the if() statement is FALSE

Syntax

if (test_expression) {
statement
} else {
statement
}

Example

val1 = 10                                    #Creating our first variable val1
val2 = 5                                     #Creating second variable val2
if (val1 > val2){                            #Executing Conditional Statement based on the comparison 
  print("Value 1 is greater than Value 2")
} else if (val1 < val2){
  print("Value 1 is less than Value 2")
}

 

Example of if else Statement

3. For Loop in R

A loop is a sequence of instructions that is repeated until a certain condition is been reached. for, while and repeat, with the additional clauses break and next are used to construct loops.

Example

These control structures in R, made of the rectangular box ‘init’, the diamond, and the rectangular box. It is executed a known number of times. for a block is been contained within curly braces.

values <- c(1,2,3,4,5) 
for(id in 1:5){ 
  print(x[id])
  }

 

For Loop in R with Example

Do you know How to Import and Transform Data with RStudio?

4. Nested Loop in R

It is similar to the standard for loop, which makes it easy to convert for loop to a foreach loop. Unlike many parallel programming packages for R, foreach doesn’t require the body of for loop to be turned into a function. … We can call this the nesting operator because it is used to create nested foreach loops

Example

mat <- matrix(1:10, 2)
for (id1 in seq(nrow(mat))) {
  for (id2 in seq(ncol(mat))) {
    print(mat[id1, id2])
  }
}

 

5. While Loop in R

The format is while(cond) expr, where cond is the condition to test and expr is an expression.
R would complain about the missing expression that was supposed to provide the required True or False and in fact, it does not know ‘response’ before using it in the loop. We can also do this because, if we answer right at first attempt, the loop will not be executed at all.

Example

val = 2.987
while(val <= 4.987) {
  val = val + 0.987
  print(c(val,val-2,val-1))
}

Let’s Perform Different Operations on Arrays in R

While Statement in R

Be sure there is a way to exit out of a while loop.

6. Repeat and Break Statement in R

We use break statement is used inside a loop (repeat, for, while) to stop the iterations and flow the control outside of the loop. While in a nested looping situation, where there is a loop inside another loop, this statement exits from the innermost loop that is being evaluated.

A repeat loop is used to iterate over a block of code multiple numbers of times. There is no condition check in a repeat loop to exit the loop. We ourselves put a condition explicitly inside the body of the loop and use the break statement to exit the loop. Failing to do so will result in an infinite loop.

Syntax

repeat {
# simulations; generate some value have an expectation if within some range,
# then exit the loop
if ((value - expectation) <= threshold) {
break
}
}

The repeat loop is an infinite loop and used in association with a break statement.

Example

Below, the code shows a repeat statement in R:

A break statement is used in a loop to stop the iterations and flow the control outside of the loop.

How to Create and Access R Matrix?

Example of Repeat Statement in R

Below the code shows repeat statement in R:

val <- 5
repeat {
  print(val)
  val <- val+1
  if (val == 10){
    break
  }
}

 

Example of R Repeat Statement in R

Example of Break Statement in R

values = 1:10
for (id in values){
  if (id == 2){
    break
  }
  print(id)
}

 

R break Statement

Recommended Reading  R Factor and Its Functions

7. Next Statement in R

next jumps to the next cycle without completing a particular iteration. In fact, it jumps to the evaluation of the condition holding the current loop. Next statement enables to skip the current iteration of a loop without terminating it.

Example 

x = 1: 4
for (i in x) {
if (i == 2) {
next
}
print(i)
}

 

Example of Next Statement in R

8. Return Statement in R

Many times, we will require functions to do some processing and return back the result. This is accomplished with the return() statement in R.

Syntax

return(expression)

Example

check <- function(x) {
if (x > 0) {
result <- "Positive"
} else if (x < 0) {
result <- "Negative"
} else {
result <- "Zero"
}
return(result)
}

> check(1)
[1] “Positive”

> check(-10)
[1] “Negative”

> check(0)
[1] “Zero”

Example of return statement in R

R Quiz

Wrapping up the use of loops in R

  • Be careful when you use repeat.
  • Make sure that termination is explicitly set by testing a condition or we can end up in an infinite loop.
  • It is better to use one or more function calls within the loop if a loop is getting (too) big.

R is the most demanding languages for Data Science. Do you know Why to choose R for Data Science

Summary

Hence, Control Structures in R are the backbone of any programming language. As it changes the flow of the program. In this R tutorial, we have studied in detail about the control statements along with its syntax and uses, loop statements and how to operate these loops with different control structures.

Hope you liked our explanation if you have any query please ask in the comment section.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.