Introduction
In this chapter, you will learn about control flow statements in R. Control flow statements allow you to control the execution of code based on conditions and loops. They are essential for writing dynamic and flexible programs. In R, the main control flow statements include if
, if-else
, ifelse
, switch
, for
, while
, and repeat
loops, as well as break
and next
statements.
if Statement
The if
statement allows you to execute a block of code only if a specified condition is TRUE
.
Syntax:
if (condition) {
# Code to execute if condition is TRUE
}
Example:
x <- 10
if (x > 5) {
print("x is greater than 5")
}
# Output: [1] "x is greater than 5"
if-else Statement
The if-else
statement allows you to execute one block of code if the condition is TRUE
and another block if the condition is FALSE
.
Syntax:
if (condition) {
# Code to execute if condition is TRUE
} else {
# Code to execute if condition is FALSE
}
Example:
x <- 3
if (x > 5) {
print("x is greater than 5")
} else {
print("x is not greater than 5")
}
# Output: [1] "x is not greater than 5"
ifelse() Function
The ifelse()
function is used for vectorized conditional operations. It applies the if-else
logic to each element of a vector.
Syntax:
ifelse(test, yes, no)
Example:
x <- c(5, 10, 15)
result <- ifelse(x > 10, "Greater than 10", "10 or less")
print(result)
# Output: [1] "10 or less" "10 or less" "Greater than 10"
switch Statement
The switch
statement allows you to execute one of several blocks of code based on the value of a variable or expression.
Syntax:
switch(expression,
case1 = {code1},
case2 = {code2},
caseN = {codeN},
default = {default_code})
Example:
fruit <- "apple"
result <- switch(fruit,
apple = "You chose an apple.",
banana = "You chose a banana.",
orange = "You chose an orange.",
"Unknown fruit")
print(result)
# Output: [1] "You chose an apple."
for Loop
The for
loop allows you to iterate over a sequence of elements and execute a block of code for each element.
Syntax:
for (variable in sequence) {
# Code to execute for each element in the sequence
}
Example:
numbers <- c(1, 2, 3, 4, 5)
for (num in numbers) {
print(num)
}
# Output:
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] 5
while Loop
The while
loop allows you to execute a block of code repeatedly as long as a specified condition is TRUE
.
Syntax:
while (condition) {
# Code to execute while the condition is TRUE
}
Example:
i <- 1
while (i <= 5) {
print(i)
i <- i + 1
}
# Output:
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] 5
repeat Loop
The repeat
loop allows you to execute a block of code repeatedly until a specified condition is met. You must use the break
statement to exit the loop.
Syntax:
repeat {
# Code to execute
if (condition) {
break # Exit the loop
}
}
Example:
i <- 1
repeat {
print(i)
i <- i + 1
if (i > 5) {
break # Exit the loop
}
}
# Output:
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] 5
break Statement
The break
statement is used within loops to immediately exit the loop.
Example:
for (i in 1:10) {
if (i == 5) {
break # Exit the loop
}
print(i)
}
# Output:
# [1] 1
# [1] 2
# [1] 3
# [1] 4
next Statement
The next
statement is used within loops to skip the current iteration and proceed to the next iteration.
Example:
for (i in 1:10) {
if (i %% 2 == 0) {
next # Skip even numbers
}
print(i)
}
# Output:
# [1] 1
# [1] 3
# [1] 5
# [1] 7
# [1] 9
Example Program with Control Flow Statements
Here is an example program that demonstrates the use of various control flow statements in R:
# R Program to Demonstrate Control Flow Statements
# Declare a vector of numbers
numbers <- c(10, 20, 30, 40, 50)
# Calculate the sum of the numbers using a for loop
sum <- 0
for (num in numbers) {
sum <- sum + num
}
print(paste("The sum of the numbers is:", sum))
# Output: [1] "The sum of the numbers is: 150"
# Using if-else statements to determine the grade based on a score
score <- 85
if (score >= 90) {
grade <- "A"
} else if (score >= 80) {
grade <- "B"
} else if (score >= 70) {
grade <- "C"
} else if (score >= 60) {
grade <- "D"
} else {
grade <- "F"
}
print(paste("The grade is:", grade))
# Output: [1] "The grade is: B"
# Using while loop to calculate factorial of a number
factorial <- function(n) {
result <- 1
i <- 1
while (i <= n) {
result <- result * i
i <- i + 1
}
return(result)
}
fact <- factorial(5)
print(paste("The factorial of 5 is:", fact))
# Output: [1] "The factorial of 5 is: 120"
# Using switch statement to choose a fruit
fruit <- "banana"
result <- switch(fruit,
apple = "You chose an apple.",
banana = "You chose a banana.",
orange = "You chose an orange.",
"Unknown fruit")
print(result)
# Output: [1] "You chose a banana."
Conclusion
In this chapter, you learned about various control flow statements in R, including if
, if-else
, ifelse
, switch
, for
, while
, and repeat
loops, as well as break
and next
statements. These control structures are essential for making decisions, iterating over sequences, and controlling the flow of your R programs. By mastering these control flow statements, you can write more dynamic, flexible, and efficient R code.