Control Statements in R
Control statements in R direct the flow of execution in a program. Here’s a comprehensive look at the key control statements available in R:
The if Statement
The if statement executes a block of code only if a specific 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") }
The if-else Statement
The if-else statement executes one block of code if the condition is true and another block if it 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 less than or equal to 5") }
The if-else if-else Statement
The if-else if-else statement allows testing multiple conditions in sequence.
Syntax:
if (condition1) { # Code to execute if condition1 is true } else if (condition2) { # Code to execute if condition2 is true } else { # Code to execute if none of the above conditions are true }
Example:
x <- 7 if (x < 5) { print("x is less than 5") } else if (x == 7) { print("x is equal to 7") } else { print("x is greater than 5 but not equal to 7") }
The ifelse Function
The ifelse function is a vectorized version of if-else, allowing you to handle vectors of values.
Syntax:
ifelse(condition, value_if_true, value_if_false)
Example:
x <- c(1, 2, 3, 4, 5) result <- ifelse(x %% 2 == 0, "Even", "Odd") print(result)
The switch Statement
The switch statement allows choosing from several options based on an index or value.
Syntax:
switch(expression, "value1" = result1, "value2" = result2, ...)
Example:
day <- 3 day_name <- switch(day, "1" = "Monday", "2" = "Tuesday","3" = "Wednesday", "4" = "Thursday", "5" = "Friday", "6" = "Saturday", "7" = "Sunday") print(day_name) # Prints "Wednesday"
while Loops
while loops execute a block of code as long as a condition is true.
Syntax:
while (condition) { # Code to execute while condition is true}
Example:
count <- 1 while (count <= 5) { print(paste("Count:", count)) count <- count + 1 }
repeat Loops
repeat loops execute a block of code indefinitely until a break condition is met.
Syntax:
repeat { # Code to execute if (condition) { break } }
Example:
count <- 1 repeat { print(paste("Count:", count)) count <- count + 1 if (count > 5) break }
break and next Statements
- break: Immediately exits the loop.
- next: Skips to the next iteration of the loop.
Example of break:
for (i in 1:10) { if (i == 5) break print(i) }
Example of next:
for (i in 1:10) {
if (i %% 2 == 0)
next
print(i)
}
Combined Control Statements
Control statements can be combined to handle more complex scenarios.
Example:
x <- 8 y <- 12 if (x > 5) { if (y < 10) { print("x is greater than 5 and y is less than 10") } else { print("x is greater than 5 but y is greater than or equal to 10") } } else { print("x is less than or equal to 5") }