R Control Structures – Decision Making and Loops in R

There are a few control structures in R that help control the flow of the program. In R, there are decision-making structures like if-else that control execution of the program conditionally.

There are also looping structures that loop or repeat code sections based on certain conditions and state.

Today, we will take a look at these control structures that R provides and learn how to use them. So, without further ado, let’s begin!

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

R Scripts

In the past tutorials, we have been using the console to run our code. While it may be easy to use, the console runs one line of code at a time. Therefore, we cannot run programs with multiple lines of code in the R-console. To solve this problem, we will write our code in R scripts and run them all at once.

R scripts are text files with R code in them. They have an extension of .r. R scripts can be edited using any text editor.

In this tutorial series, we will be using Rstudio to edit and run our R scripts.

To run a part of your R file in Rstudio, select the code and press Ctrl+Enter.

Control Structures in R

R provides different control structures that can be used on their own and even in combinations to control the flow of the program. These control structures are:

  1. If – else
  2. ifelse() function
  3. Switch
  4. For loops
  5. While loops
  6. Break statement
  7. Next statement
  8. Repeat loops

Let’s take a look at these structures one at a time:

1. if – else

The if-else in R enforce conditional execution of code. They are an important part of R’s decision-making capability. It allows us to make a decision based on the result of a condition. The if statement contains a condition that evaluates to a logical output. It runs the enclosed code block if the condition evaluates to TRUE. It skips the code block if the condition evaluates to FALSE.

We can use the if statement on its own like:

Code:

a <- 5
b <- 6
if(a<b){
 print("a is smaller than b")
}

Output:

if() - control structures in r

You must check R Data Types as it plays a vital role in Control Structures.

We use the else statement with the if statement to enact a choice between two alternatives. If the condition within the if statement evaluates to FALSE, it runs the code within the else statement. For example:

Code:

if(a>b){
  print("a is greater than b")
} else{
  print("b is greater than a")
}

Output:

if-else - control structures in r

We can use the else if statement to select between multiple options. For example:

Code:

a <- 5
b <- 5
if(a<b){
  print("a is smaller than b")
} else if(a==b) {
  print("a is equal to b")
} else {
  print("a is greater than b")
}

Output:

 else if() - control structures in r

2. ifelse() Function

The ifelse() function acts like the if-else structure. The following is the syntax of the ifelse() function in R:

ifelse(condition, exp_if_true, exp_if_false)

Where condition is the condition that evaluates to either TRUE or FALSE,
exp_if_true is the expression that is returned if the condition results in TRUE,
exp_if_false is the expression that is returned if the condition results in FALSE.

Code:

ifelse(a<7,"a is less than 7","a is greater than 7")

Output:

ifelse() function - control structures in r

3. switch

The switch is an easier way to choose between multiple alternatives than multiple if-else statements. The R switch takes a single input argument and executes a particular code based on the value of the input. Each possible value of the input is called a case. For example:

Code:

a <- 4
switch(a,
       "1"="this is the first case in switch",
       "2"="this is the second case in switch",
       "3"="this is the third case in switch",
       "4"="this is the fourth case in switch",
       "5"="this is the fifth case in switch"
       )

Output:

switch() - control structures in r

4. for loops

The for loop in R, repeats through sequences to perform repeated tasks. They work with an iterable variable to go through a sequence. The following is the syntax of for loops in R:

for(variable in sequence){
Code_to_repeat
}

Where variable is the iterative variable,
sequence is the sequence which we need to loop through,
Code_to_repeat is the code that runs every iteration.

Code:

vec <- c(1:10)
for(i in vec){
  print(vec[i])
}

Output:

for loop - control structures in r

5. while Loops

The while loop in R evaluates a condition. If the condition evaluates to TRUE it loops through a code block, whereas if the condition evaluates to FALSE it exits the loop. The while loop in R keeps looping through the enclosed code block as long as the condition is TRUE. This can also result in an infinite loop sometimes which is something to avoid. The while loop’s syntax is as follows:

while(condition){
code_to _run
}

Where condition is the condition to run the loop,
code_to_run is the code block that runs if the condition evaluates to TRUE.

Code:

i <- 0
while(i<10){
  print(paste("this is iteration no",i))
  i <- i+1
}

Output:

while loop - control structures in r

6. break Statement

The break statement can break out of a loop. Imagine a loop searching a specific element in a sequence. The loop needs to keep going until either it finds the element or until the end of the sequence. If it finds the element early,  further looping is not needed. In such a case, the R break statement can “break” us out of the loop early. For example:

Code:

for(i in vec){
  print(paste("this is iteration no ", i))
  if(i==7){
    print("break!!")
    break
  }
}

Output:

break statement - control structures in r

7. next Statement

The next statement in R causes the loop to skip the current iteration and start the next one. For example:

Code:

for(i in vec){
  if(i==5 || i==7){
    print("next!!")
    next
  }
  print(paste("this is iteration no", i))
}

Output:

next statement - control structures in r

8. repeat loop

The repeat loop in R initiates an infinite loop from the get-go. The only way to get out of the loop is to use the break statement. The repeat loop is useful when you don’t know the required number of iterations. For example:

Code:

vec2 <- 1:40
x <- 15
i <- 1
repeat{
  if(i == x){
    print("found it!!")
    break
  }
  print("not found!")
  i <- i+1
}

Output:repeat loops - control structures in r

Summary

Decision-making is an important feature of any programming language. It allows you to change the sequence of execution of code based on certain conditions. Today, we studied the structures and statements that control the flow of an R program.

These structures can be used in all combinations with each-other for different scenarios and implementations. The best way to learn more about their combinations and their results is to practice.

If you find any difficulty while practicing R control structures, ask your doubts from TechVidvan Experts.

Happy Coding!!

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.