Table of contents
1.
Introduction 
2.
Control Statements in R
2.1.
If Statement
2.2.
If-else Statement
2.3.
If-else if-else Statement
2.4.
For Loop
2.5.
Nested Loop
2.6.
While Loop
2.7.
Repeat loops
2.8.
Next Statement
2.9.
Break Statement
2.10.
Return Statement
3.
Use Cases of the Control Statements in R
4.
Frequently Asked Questions
4.1.
Can we have multiple conditions in a single if-else statement in R?
4.2.
Can an if statement be nested within another if statement in R?
4.3.
What is the purpose of the return statement in R?
4.4.
How can the next statement be used in R?
4.5.
What is the difference between a while loop and a repeat loop?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

What are the Control Statements in R?

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction 

In this article, we will learn about control structures in the R Programming Language. Control structures allow you to control the flow of execution of R statements. We will look at the if-else statement, for loops, nested loops, while loops, repeat loops, next, return and break statements etc. We will also look at examples for clear understanding. Let’s start the article.

What are the Control Statements in R?

Let us understand briefly what Control statements are.

Control Statements in R

What control statements are is quite evident by their name. Control statements are used to alter the flow of execution. It enables you to put some logic into your code. It helps reduce repetitive code. It allows the execution of lines of code based on certain conditions. It gives the programmer control over how many times a program line should be executed. Control structures are used in writing, functions or longer expressions.

If Statement

The ‘if’ control statement allows you to execute a code block if a given condition is true. When the condition is true, the code block is executed. When it is false, the code block is skipped.

Syntax

if(Condition){
	statements
	....
	# code will be executed if the condition is true.
}


Let’s see an example of the same.

Code

weather <- "rainy"
if(weather == "rainy"){
	print("Weather today is rainy")
}


Output

example of if statement

If-else Statement

The 'if-else' statement is the most commonly used in programming. It allows you to test a condition and act accordingly. It will enable the user to execute different statements based on whether the condition is true or false.

Syntax

if(Condition){
	statements
	....
	# code will be executed if the condition is true.
}
else{
	statements
	....
	# code will be executed if the condition is false.
}


Let’s see an example of the same.

Code

num1 = 20                                   
num2 = 10                                     
if (num1 > num2){                            
	print("number 1 is greater than number 2")
}
else (val1 < val2){
	print("number 1 is less than number 2")
}


Output

example of if else statement

If-else if-else Statement

The ‘If-else if-else’ allows you to test multiple conditions. Once an if statement is true, the code for that statement will be executed. Rest all if conditions will be skipped. And if none of the if conditions is true, then the last else part will be executed.

Syntax

if(Condition 1){
	statements
	....
	# code will be executed if condition1 is true.
}
else if(Condition 2){
	statements
	....
	# code will be executed if condition 2 is true.
}
else {
	statements
	....
	# code will be executed if all the if conditions are false.
}


Let’s see an example of the same.

Code

weather <-"rainy"
if(weather == "windy"){
	print("Today weather is windy")
} 
else if(weather == "rainy"){
	print("Today weather is rainy!!")
} 
else {
	print("weather is as clear")
}


Output

example of if else if statement

For Loop

The ‘for’ loop allows you to iterate over a sequence. The loop continues until a specific condition is reached. It can iterate over objects for a fixed number of times.

Syntax

for(value in sequence){
	statements
	....
	....
}


Let’s see an example of the same.

Code

list <- letters[0:5]
for(i in list){
	print(i)
}


Output

example of for loop

Nested Loop

Nested loops are nothing but loops inside a loop. Nested loops are commonly used to iterate on matrices.

Syntax

for(value in sequence){
	for(value in sequence){
		statements
		....
		....
	}
}


Let’s see an example of the same.

Code

mat <- matrix(2:10, 3)
for (r in seq(nrow(mat))) {
	for (c in seq(ncol(mat))) {
		print(mat[r, c])
	}
}


Output

example of nested loop

While Loop

The ‘while’ loop will keep running the code block as long as the condition remains true. First, it checks the condition. If the condition is true, it will execute the code block. Now it will recheck the condition. Thus, the loop keeps running until the condition turns out to be false.

Syntax

while(condition){
	statement
	....
	# code will be executed if the condition is true.
}

 

Let’s see an example of the same.

Code

x = 1
while(x <= 5){
	print(x)
	x = x + 1
}

 

Output

example of while loop

Repeat loops

The ‘repeat’ loop is an infinite loop. We can exit this infinite loop by using the break statement. It can be used when the number of iterations is unknown. We can specify a condition when we want to end the loop. When the condition is true, we can call the break statement.

Syntax

repeat { 
	statements
	....
 
	if(condition) {
		break
	}
}

 

Let’s see an example of the same.

Code

x = 1

repeat{
	print(x)
	x = x + 1
	if(x > 5){
  		break
	}
}

 

Output

example of repeat loop

Next Statement

The ‘next’ statement skips the current iteration and moves to the next one. It does not terminate the loop. All the statements after the next statement will not be executed.

Let’s see an example of the same.

Code

# Defining vector
vec <- 1:5

# Print all numbers except 3
for(i in vec){
	if(i == 3){
		next  #skips this iteration
	}
	print(i)
}


Output

example of next statement

Break Statement

The ‘break’ statement can be used to exit from the loop. It ends the loop and starts running the immediate next statement after the loop. It is commonly used with conditional statements to leave loops based on certain conditions.

Let’s see an example of the same.

Code

for (i in 1:10) {
	# Print the current number
	print(i)
	# If the number is 5, break out of the loop
	if (i == 5) {
  		break
	}
}
print("the loop was terminated ")


Output

example of break statement

Return Statement

The return statement is used to exit a function. It can also return values when required. It immediately terminates the function when encountered.

Syntax

return(expression)


Let’s see an example of the same.

Code

evenodd <- function(x){
	if(x %% 2 == 0){
		return("Even")
	}
	else{
		return("Odd")
	}
}
evenodd(2)
evenodd(3)


Output

example of retun statement

Use Cases of the Control Statements in R

  1. Decision making: Control statements like if-else statements are used to make decisions based on certain conditions.
     
  2. Looping: for loops, while loops and repeat loops enable you to repeat a block of code multiple times.
     
  3. Program flow control: The break and next statements provide control over program flow within loops. The break statement allows you to exit the loop. The Next statement allows you to skip the current iteration.
     
  4. Function control:  The return statement can be used within functions to return a value. 

Frequently Asked Questions

Can we have multiple conditions in a single if-else statement in R?

Yes, we can have multiple conditions in a single if-else statement in R. This can be done using logical operators such as && AND or || (OR).

Can an if statement be nested within another if statement in R?

Yes, you can nest an if statement in another if statement. This allows you to create more complex decision-making structures. It allows you to add multiple conditions.

What is the purpose of the return statement in R?

The return statement is used to exit a function. It can also return values when required. It immediately terminates the function when encountered.

How can the next statement be used in R?

The next treatment allows you to skip the remaining course within a loop. It moves to the next iteration whenever encountered.

What is the difference between a while loop and a repeat loop?

While the loop executes the statements as long as the condition is true, in contrast, the Repeat loop executes the statements until a specified condition is met.

Conclusion

In this article, we learned about Control Statements in R. We clearly understood what each control statement means. We learned the syntax and its implementation. Finally, we looked at examples demonstrating the use of each control statement.

Recommended Articles:


And many more on our platform Coding Ninjas Studio.
 

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your coding ability, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. Take a look at the problemsinterview experiences, and interview bundles for placement preparations.

However, consider our paid courses to give your career an edge over others!

Happy Learning!

Live masterclass