Control Structures in R – Master the Working of Loops in R!

In order to control the execution of the expressions flow in R, we make use of the control structures. These control structures are also called as loops in R. There are eight types of control structures in R:

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

We will study their examples as well as its execution flow. So, let’s start with the tutorial!

Control Structures in R Programming

R provides various standard control structures for our requirements. The expr expression consists of multiple statements that can be enclosed in braces {}.

It is more efficient to use built-in functions in R rather than control structures, whenever possible. This facilitates the flow of execution to be controlled inside a function.

Control structures define the flow of the program. The decision is then made after the variable is assessed. 

Wait! Have you checked – R Factor Functions Tutorial

List of R Control Structures with Examples

Now we will discuss the control structures in R one by one in detail:

Control Structures in R Programming

1. if Condition in R

This task is carried out only if this condition is returned as TRUE. 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"))

Output:

values 1:10

You must check R Data Types as it plays an important role in Control Structures

2. if-else Condition in R

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

  • The keyword else, placed after the first code block.
  • The second block of code, contained within braces, that has to be carried out, 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")
}

Output:

val1 and val2

3. for Loop in R

A loop is a sequence of instructions that is repeated until a certain condition is 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’ and the diamond. It is executed a known number of times. for is a block that is contained within curly braces.

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

Output:

values c 12345

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 a 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])
  }
}

Output:

Matrix 1:2, 10

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

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))
}

Output:

val=2.987

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

6. repeat and break Statement in R

We use break statement 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 is 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.

Example of Repeat Statement in R:

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

Output:

val<-5 (Control Structures in R)

Example of Break Statement in R:

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

Output:

values 1:10 for id in values

Recommended Reading – R Vector 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)
}

Output:

x = 1:4 (Control Structures in R)

8. return Statement in R

Many times, we will require some functions to do 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)
}

In the console window, we type:

> check(1)
> check(-10)
> check(0)

Output:

check <- function(x) - Control Structures in R

R Quiz

Wrapping up the Use of Loops in R

  • Be careful when you use the repeat statement.
  • 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.

Summary

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 and how to operate these loops with different control structures.

Now, it’s the time for exploring the Usage of R Function

Hope you liked our explanation. Any queries? Feel free to share 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.