Explain different control statements in R.
Solution:
Control statements in R are used to manage the flow of execution in a program based on specified
conditions. They help in decision-making, iterating over data, and controlling program logic. Below are
the key control statements in R, with their purposes and examples:
1. if Statement
The if statement executes a block of code only if a specified condition is TRUE.
Syntax:
if (condition) {
# Code to execute if the condition is TRUE
}
Example:
x <- 15
if (x > 10) {
print("x is greater than 10")
}
Output: [1] "x is greater than 10"
2. if-else Statement
The if-else statement allows alternative actions if the condition in if is FALSE.
Syntax:
if (condition) {
# Code to execute if condition is TRUE
} else {
# Code to execute if condition is FALSE
}
Example:
x <- 5
if (x > 10) {
print("x is greater than 10")
} else {
print("x is less than or equal to 10")
}
Output: [1] "x is less than or equal to 10"
3. for Loop
The for loop iterates over elements in a sequence (e.g., a vector, list).
Syntax:
for (value in sequence) {
# Code to execute for each element in the sequence
}
Example:
for (i in 1:5) {
print(i)
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
4. while Loop
The while loop repeatedly executes a block of code as long as a condition is TRUE.
Syntax:
while (condition) {
# Code to execute while condition is TRUE
}
Example:
x <- 1
while (x <= 5) {
print(x)
x <- x + 1
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
5. repeat Loop
The repeat loop runs indefinitely unless terminated using a break statement.
Syntax:
repeat {
# Code to execute
if (condition) {
break
}
}
Example:
x <- 1
repeat {
print(x)
if (x == 5) break
x <- x + 1
}
Output:
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5