Control Statements
Control statements are constructs used to manage the flow and execution of a program based on specified conditions. These structures enable decision-making after evaluating variables. This document covers all control statements in R with examples.
In R programming, there are 8 main types of control statements:
- if condition
- if-else condition
- for loop
- nested loops
- while loop
- repeat and break statement
- return statement
- next statement
if, if-else, if-else-if ladder, nested if-else, and switch
1. if Statement
The if statement is a decision control instruction that evaluates a condition enclosed within parentheses. If the condition is TRUE, the subsequent block of statements is executed; otherwise, the block is skipped.
Syntax:
if (condition) {
# Statements to execute if the condition is TRUE
}
Example:
x <- 25
y <- 15
# Condition is TRUE
if (x > y) {
result <- x - y
print("x is greater than y")
print(paste("Difference is:", result))
}
# Condition is FALSE
if (x < y) {
result <- y - x
print("x is less than y")
print(paste("Difference is:", result))
}
Output:
[1] "x is greater than y"
[1] "Difference is: 10"
2. if-else Statement
The if-else statement provides an optional else block that executes if the condition in the if block is FALSE.
Syntax:
if (condition) {
# Statements if condition is TRUE
} else {
# Statements if condition is FALSE
}
Example:
x <- 18
y <- 22
if (x > y) {
result <- x - y
print("x is greater than y")
print(paste("Difference is:", result))
} else {
result <- y - x
print("x is not greater than y")
print(paste("Difference is:", result))
}
Output:
[1] "x is not greater than y"
[1] "Difference is: 4"
3. if-else-if Ladder
The if-else-if ladder evaluates multiple conditions sequentially. The first TRUE condition’s corresponding block is executed, and the remaining conditions are ignored.
Syntax:
if (condition1) {
# Statements if condition1 is TRUE
} else if (condition2) {
# Statements if condition2 is TRUE
} else {
# Statements if none of the above conditions are TRUE
}
Example:
a <- 45
b <- 55
c <- 65
if (a > b && b > c) {
print("a > b > c is TRUE")
} else if (a < b && b > c) {
print("a < b > c is TRUE")
} else if (a < b && b < c) {
print("a < b < c is TRUE")
}
Output:
[1] "a < b < c is TRUE"
4. Nested if-else Statement
A nested if-else structure contains an if-else block inside another if or else block. This allows evaluation of additional conditions within a parent block.
Syntax:
if (parent_condition) {
if (child_condition1) {
# Statements if both conditions are TRUE
} else {
# Statements if parent_condition is TRUE and child_condition1 is FALSE
}
} else {
if (child_condition2) {
# Statements if parent_condition is FALSE and child_condition2 is TRUE
} else {
# Statements if both parent_condition and child_condition2 are FALSE
}
}
Example:
x <- 5
y <- 10
if (x == 5) {
if (y == 10) {
print("x: 5, y: 10")
} else {
print("x: 5, y is not 10")
}
} else {
if (x == 10) {
print("x: 10, y: 5")
} else {
print("x is not 5 or 10")
}
}
Output:
[1] "x: 5, y: 10"
5. switch Statement
The switch statement evaluates an expression against a list of cases and executes the matching case. If no match is found, NULL is returned.
Syntax:
switch(expression, case1, case2, ..., caseN)
Example :
# Match by index
result1 <- switch(
3, # Expression
"Case 1", # Case 1
"Case 2", # Case 2
"Case 3" # Case 3
)
print(result1)
# Match by name
result2 <- switch(
"Option2", # Expression
Option1 = "First Option",
Option2 = "Second Option",
Option3 = "Third Option"
)
print(result2)
# No match case
result3 <- switch(
"InvalidOption", # Expression
Option1 = "First Option",
Option2 = "Second Option"
)
print(result3)
Output:
[1] "Case 3"
[1] "Second Option"
NULL
For Loop
The for loop in R is a powerful construct used to iterate over elements of a vector, list, data frame, matrix, or other objects. It allows repeated execution of a set of statements for each element in the object. Being an entry-controlled loop, the condition is evaluated before the loop body executes. If the condition is false, the loop does not execute.
Syntax of a For Loop in R:
for (var in vector) {
# Statements to execute
}
Here:
var takes on each value from vector sequentially during each iteration.
- The statements inside the loop body are evaluated for each value of
var.
Iterating Over a Range in R
Example:
# R Program to demonstrate iterating over a range
for (i in 1:5) {
print(i * 2)
}
Output:
[1] 2
[1] 4
[1] 6
[1] 8
[1] 10
In this example, the range 1:5 was used as the vector, and each element was multiplied by 2.
Using the Concatenate Function in a For Loop
Example:
# R Program to demonstrate the use of concatenate
for (i in c(5, 10, -15, 20)) {
print(i * 3)
}
Output:
[1] 15
[1] 30
[1] -45
[1] 60
Here, we use c() to define a vector inside the loop.
Defining the Vector Outside the Loop
Example:
# R Program to demonstrate a vector outside the loop
nums <- c(4, 7, -2, 12)
for (i in nums) {
print(i + 5)
}
Output:
[1] 9
[1] 12
[1] 3
[1] 17
The vector is defined outside and used in the loop.
Nested For Loops in R
R supports nesting one loop inside another. For instance, a for loop can exist within another for loop.
Example:
# R Program to demonstrate nested for loops
for (i in 1:3) {
for (j in 1:i) {
print(i + j)
}
}
Output:
[1] 2
[1] 3
[1] 4
[1] 4
[1] 5
[1] 6
While Loop
The while loop in R is used when the exact number of iterations is not known beforehand. It executes the same code repeatedly until a specified stop condition is met. Unlike some other loops, the while loop checks the condition before executing the loop body, resulting in an extra condition check (n+1 times) compared to the n iterations.
Syntax of while Loop in R:
while (test_expression) {
# Statements
update_expression
}
Execution Flow of while Loop:
- Control enters the
while loop.
- The condition (test_expression) is evaluated.
- If the condition is true, control enters the loop body.
If the condition is false, control exits the loop.
- The statements inside the loop body are executed.
- The update expression is evaluated.
- Control returns to Step 2 to recheck the condition.
- The loop ends when the condition becomes false, and control exits the loop.
Key Points About while Loop in R:
- The loop runs until the given condition is false.
- If the condition is initially false, the loop body will not execute at all.
- Ensure there’s a mechanism to make the condition false; otherwise, the loop will run indefinitely.
Example 1: Print a String Multiple Times
# R program to illustrate while loop
message <- "Learning R is fun!"
counter <- 1
# Test expression
while (counter <= 5) {
print(message)
# Update expression
counter <- counter + 1
}
Output:
[1] "Learning R is fun!"
[1] "Learning R is fun!"
[1] "Learning R is fun!"
[1] "Learning R is fun!"
[1] "Learning R is fun!"
Example 2: Incrementing a Value
# R program to increment and print values
number <- 1
index <- 1
# Test expression
while (index <= 5) {
print(number)
# Update expressions
number <- number + 2
index <- index + 1
}
Output:
[1] 1
[1] 3
[1] 5
[1] 7
[1] 9
Using break in a while Loop
The break statement is used to terminate the loop based on a specific condition, even if the original condition of the loop is still true.
# R program to demonstrate break in while loop
text <- "This will stop soon"
count <- 1
while (count <= 5) {
print(text)
if (count == 3) {
break
}
# Update expression
count <- count + 1
}
Output:
[1] "This will stop soon"
[1] "This will stop soon"
[1] "This will stop soon"
Using next in a while Loop
The next statement is used to skip the current iteration and proceed to the next one.
# R program to demonstrate next in while loop
x <- 1
while (x <= 10) {
if (x == 4) {
x <- x + 1
next
}
print(paste("Current number is:", x))
x <- x + 1
}
Output:
[1] "Current number is: 1"
[1] "Current number is: 2"
[1] "Current number is: 3"
[1] "Current number is: 5"
[1] "Current number is: 6"
[1] "Current number is: 7"
[1] "Current number is: 8"
[1] "Current number is: 9"
[1] "Current number is: 10"
Example: while Loop with if–else Statement
x <- 1
while (x <= 8) {
if (x %% 2 == 0) {
print(paste(x, "is an even number"))
} else {
print(paste(x, "is an odd number"))
}
x <- x + 1
}
Output:
[1] "1 is an odd number"
[1] "2 is an even number"
[1] "3 is an odd number"
[1] "4 is an even number"
[1] "5 is an odd number"
[1] "6 is an even number"
[1] "7 is an odd number"
[1] "8 is an even number"
Repeat loop
The repeat loop in R is used to execute a block of code repeatedly until a break statement is encountered. Unlike other loops, the repeat loop does not require a condition to be defined at the start; instead, it continues indefinitely until a specific condition within the loop evaluates to TRUE, causing the break statement to terminate the loop.
It is simple to create infinite loops in R using the repeat loop, so careful use of the break statement is essential. The keyword used for the repeat loop is repeat.
Syntax
repeat {
# Code to execute
if (condition) {
break # Exits the loop
}
}
Example 1: Print a Phrase Multiple Times
# R program to demonstrate repeat loop
message <- "Learn R"
counter <- 1
# Repeat block
repeat {
print(message)
# Update counter
counter <- counter + 1
# Exit condition
if (counter > 3) {
break
}
}
Output:
[1] "Learn R"
[1] "Learn R"
[1] "Learn R"
Example 2: Incrementing a Number
# R program to demonstrate repeat loop
number <- 10
iteration <- 1
# Repeat block
repeat {
print(number)
# Update values
number <- number + 5
iteration <- iteration + 1
# Exit condition
if (iteration > 4) {
break
}
}
Output:
[1] 10
[1] 15
[1] 20
[1] 25
goto statement
In programming, a “goto” statement is a command that transfers control of execution to a specified line or block of code. This can be helpful when there is a need to jump between different parts of the code without using functions or introducing an abnormal shift.
Unfortunately, the R programming language does not support the goto statement. However, its behavior can be simulated using alternative constructs like:
if and else statements
- Loop control statements (
break, next, return)
Below, we explore how these methods can be used to replicate the functionality of goto.
Example 1: Check Whether a Number is Even or Odd
num <- 7
if ((num %% 2) == 0) {
print("The number is even")
} else {
print("The number is odd")
}
Output:
[1] "The number is odd"
Explanation:
Using goto:
- Define two code blocks,
EVEN and ODD.
- Evaluate the condition for the number (
num).
- If even, jump to the
EVEN block.
- If odd, jump to the
ODD block
Without goto:
- Evaluate the condition directly using an
if-else statement.
- Execute the corresponding block of code.
Break and Next statements
In R programming, a loop is a control structure used to execute a block of code repeatedly. Loops are essential programming concepts that facilitate iteration or cycling through code.
Jump statements are often used in loops to control their behavior. These statements can either terminate a loop or skip certain iterations based on specific conditions. The two commonly used jump statements in R are:
- Break Statement
- Next Statement
Role of Break and Next Statements
- The
break statement is used to exit a loop prematurely when a condition is met.
- The
next statement skips the current iteration and proceeds to the next one in the loop.
R provides three types of loops: repeat, for, and while, which can use break and next statements for better control.
Break Statement in R
The break statement is used to terminate the loop at a specific condition and continue with the rest of the program.
Syntax:
if (test_expression) {
break
}
Example:
# Example of Break Statement in For Loop
numbers <- 1:10
for (num in numbers) {
if (num == 4) {
print(paste("Exiting the loop when num =", num))
break
}
print(paste("Current number:", num))
}
Output:
[1] "Current number: 1"
[1] "Current number: 2"
[1] "Current number: 3"
[1] "Exiting the loop when num = 4"
Break Statement in R with While Loop
# Example of Break Statement in While Loop
count <- 1
while (count <= 7) {
print(count)
if (count == 5) {
print("Breaking the loop at count = 5")
break
}
count <- count + 1
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] "Breaking the loop at count = 5"
Next Statement in R
The next statement is used to skip the current iteration in the loop and proceed to the next iteration without terminating the loop.
Syntax:
if (test_condition) {
next
}
Next Statement in R with While Loop
# Example of Next Statement in While Loop
counter <- 1
while (counter <= 5) {
counter <- counter + 1
if (counter == 3) {
next
}
print(counter)
}
Output:
[1] 2
[1] 4
[1] 5
[1] 6